How to Use .env File with Flask for Environment Variables
To use a
.env file with Flask, install the python-dotenv package and create a .env file with your variables. Then, load these variables in your Flask app by calling load_dotenv() before accessing them via os.getenv().Syntax
Use the python-dotenv package to load environment variables from a .env file into your Flask app.
from dotenv import load_dotenv: Imports the function to load the .env file.load_dotenv(): Loads the variables from the .env file into the environment.os.getenv('VAR_NAME'): Retrieves the value of the environment variableVAR_NAME.
python
from dotenv import load_dotenv import os load_dotenv() # Load variables from .env file secret_key = os.getenv('SECRET_KEY') print(f"Secret Key: {secret_key}")
Output
Secret Key: mysecretvalue
Example
This example shows a simple Flask app that loads a secret key from a .env file using python-dotenv. The secret key is then used to configure the Flask app.
python
from flask import Flask from dotenv import load_dotenv import os load_dotenv() # Load environment variables from .env file app = Flask(__name__) app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') @app.route('/') def home(): return f"Secret Key is: {app.config['SECRET_KEY']}" if __name__ == '__main__': app.run(debug=True)
Output
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Secret Key is: mysecretvalue
Common Pitfalls
Not installing python-dotenv: Without this package, load_dotenv() won't work.
Forgetting to call load_dotenv(): Environment variables won't load if you skip this step.
Incorrect .env file location: The .env file should be in your project root or specify the path in load_dotenv().
Not restarting the Flask app after changes: Changes in .env require app restart to take effect.
python
## Wrong way (missing load_dotenv): from flask import Flask import os app = Flask(__name__) app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') # Will be None if .env not loaded # Correct way: from dotenv import load_dotenv load_dotenv() # Must call this before accessing env vars
Quick Reference
- Install
python-dotenvwithpip install python-dotenv. - Create a
.envfile in your project root with key-value pairs likeSECRET_KEY=mysecretvalue. - Call
load_dotenv()early in your Flask app to load variables. - Access variables with
os.getenv('VAR_NAME'). - Restart your Flask app after editing the
.envfile.
Key Takeaways
Install and use python-dotenv to load .env files in Flask projects.
Always call load_dotenv() before accessing environment variables.
Keep your .env file in the project root or specify its path explicitly.
Access environment variables with os.getenv() for secure configuration.
Restart your Flask app after changing the .env file to apply updates.