Flask Environment Variables
An environment variable is a setting outside the code. The app reads it with os.getenv.
Set a variable in the terminal
This terminal line sets FLASK_GREETING to Hi, then starts the app. The app reads the value when it runs.
FLASK_GREETING="Hi" python app.pyMake the app
This line imports os and Flask together. The route below reads the variable.
import os
from flask import Flask
app = Flask(__name__)Read the greeting
The view reads FLASK_GREETING with a default. No variable is set here, so the default shows.
@app.route("/")
def home():
return os.getenv("FLASK_GREETING", "Hello, Flask!")Ask for the greeting
The test client asks for / and prints the greeting. The default shows, because no variable is set.
client = app.test_client()
print(client.get("/").data.decode())Example
import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return os.getenv("FLASK_GREETING", "Hello, Flask!")
client = app.test_client()
print(client.get("/").data.decode())Key points
- Environment variables live in the terminal, not in a file.
- os.getenv("FLASK_GREETING", "Hello, Flask!") reads one, with a default.
- A missing variable returns the default.
- Secrets belong in variables, not in code.
In this example, the view reads FLASK_GREETING with the default "Hello, Flask!". No variable is set when the program runs, so the default shows. The test client asks for / and prints the greeting.
Note
Set a variable before starting the server, like FLASK_GREETING="Hi" python app.py.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does os.getenv("FLASK_GREETING", "Hello, Flask!") return when the variable is missing?