SoFunction
Updated on 2025-04-04

How to manage environment variables using Python Dotenv library

Manage environment variables using Python Dotenv library

When developing Python applications, managing configuration information (such as API keys, database connection strings, etc.) is a common requirement. To ensure security and flexibility, hard-code these sensitive information in code is not usually recommended. At this time,dotenvThe database comes in handy. This article will describe how to use itpython-dotenvlibrary to manage environment variables.

What is Dotenv?

DotenvIt's a.envTools for loading environment variables into the application environment in the file. It originally originated from the Ruby ecosystem and was later ported to a variety of programming languages, including Python. By usingdotenvYou can store configuration information in.envin the file and automatically load these variables when the application starts.

Install Dotenv

First, you need to install itpython-dotenvlibrary. You can install it through pip:

pip install python-dotenv

Create .env file

Create a file named .env in the root directory of your project. This file will contain your environment variables, one variable per line, in the format KEY=VALUE, for example:

DATABASE_URL=postgres://user:password@localhost:5432/mydatabase
SECRET_KEY=mysecretkey
DEBUG=True

Loading .env files in Python

In your Python script, you can use the dotenv library to load variables in the .env file. Here is a simple example:

from dotenv import load_dotenv
import os
# Load .env fileload_dotenv()
# Access environment variablesdatabase_url = ('DATABASE_URL')
secret_key = ('SECRET_KEY')
debug = ('DEBUG')
print(f"Database URL: {database_url}")
print(f"Secret Key: {secret_key}")
print(f"Debug Mode: {debug}")

Summarize

usepython-dotenvThe library can easily manage environment variables and avoid hard-code sensitive information in code. By storing configuration information in the **.env** file, you can easily switch configurations between different environments (development, testing, production) while keeping your code neat and secure.

This is the end of this article about using the Python Dotenv library to manage environment variables. For more related contents of the Python Dotenv library environment variables, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!