Consider this Flask app snippet that reads an environment variable to configure debug mode:
import os
from flask import Flask
app = Flask(__name__)
app.config['DEBUG'] = os.getenv('FLASK_DEBUG', 'False') == 'True'
@app.route('/')
def home():
return 'Debug is ' + str(app.config['DEBUG'])What will be the output if the environment variable FLASK_DEBUG is set to True?
import os from flask import Flask app = Flask(__name__) app.config['DEBUG'] = os.getenv('FLASK_DEBUG', 'False') == 'True' @app.route('/') def home(): return 'Debug is ' + str(app.config['DEBUG'])
Remember that environment variables are strings and the code compares the string value.
The environment variable FLASK_DEBUG is read as a string. The code compares it to the string 'True'. If it matches, app.config['DEBUG'] becomes True (boolean). So the output shows Debug is True.
You want to load environment variables from a .env file in your Flask app. Which code snippet correctly does this using python-dotenv?
Check the official python-dotenv package usage.
The correct way to load environment variables from a .env file is to use from dotenv import load_dotenv and then call load_dotenv(). Other options either use wrong module names or functions that don't exist.
Given this Flask app code:
from dotenv import load_dotenv
import os
from flask import Flask
load_dotenv()
app = Flask(__name__)
@app.route('/')
def index():
return os.getenv('MY_VAR', 'Not Set')You update the .env file to change MY_VAR but the app still returns the old value without restarting. Why?
from dotenv import load_dotenv import os from flask import Flask load_dotenv() app = Flask(__name__) @app.route('/') def index(): return os.getenv('MY_VAR', 'Not Set')
Think about when environment variables are loaded and how Flask apps run.
Environment variables loaded by load_dotenv() happen once when the app starts. If you change the .env file later, the app does not reload those variables automatically. You must restart the app to see changes.
Consider this Flask app snippet:
import os
from flask import Flask
os.environ['SECRET_KEY'] = 'supersecret'
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'defaultkey')What is the value of app.config['SECRET_KEY']?
import os from flask import Flask os.environ['SECRET_KEY'] = 'supersecret' app = Flask(__name__) app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'defaultkey')
Remember how os.environ and os.getenv work.
The environment variable SECRET_KEY is set in os.environ before the Flask app reads it. So os.getenv('SECRET_KEY') returns 'supersecret'.
You want to keep sensitive environment variables like SECRET_KEY safe in production. Which approach is best practice?
Think about security and version control exposure.
Best practice is to set sensitive environment variables directly on the production environment (server or container) so they are not stored in code or version control. This reduces risk of accidental exposure.