Bird
Raised Fist0
Flaskframework~20 mins

Environment variable management in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Environment Variable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does Flask access environment variables in this code?

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?

Flask
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'])
ADebug is True
BDebug is False
CDebug is None
DDebug is 'True'
Attempts:
2 left
💡 Hint

Remember that environment variables are strings and the code compares the string value.

📝 Syntax
intermediate
2:00remaining
Which option correctly loads environment variables from a .env file in Flask?

You want to load environment variables from a .env file in your Flask app. Which code snippet correctly does this using python-dotenv?

A
from dotenv import load_dotenv
load_dotenv()

app = Flask(__name__)
B
import dotenv
dotenv.load()

app = Flask(__name__)
C
from flask_dotenv import load_dotenv
load_dotenv()

app = Flask(__name__)
D
import os
os.load_dotenv()

app = Flask(__name__)
Attempts:
2 left
💡 Hint

Check the official python-dotenv package usage.

🔧 Debug
advanced
2:00remaining
Why does this Flask app fail to read updated environment variables after .env change?

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?

Flask
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')
AThe load_dotenv() function does not read .env files automatically.
BFlask blocks environment variable access inside route functions.
Cos.getenv caches values and does not reflect changes until Python interpreter restarts.
DEnvironment variables are loaded once at startup; changes in .env require app restart to reload.
Attempts:
2 left
💡 Hint

Think about when environment variables are loaded and how Flask apps run.

❓ state_output
advanced
2:00remaining
What is the value of app.config['SECRET_KEY'] after this code runs?

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']?

Flask
import os
from flask import Flask

os.environ['SECRET_KEY'] = 'supersecret'
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'defaultkey')
ANone
Bdefaultkey
Csupersecret
DRaises KeyError
Attempts:
2 left
💡 Hint

Remember how os.environ and os.getenv work.

🧠 Conceptual
expert
3:00remaining
Which approach best secures sensitive environment variables in Flask deployment?

You want to keep sensitive environment variables like SECRET_KEY safe in production. Which approach is best practice?

AStore sensitive variables in a .env file committed to version control for easy access.
BSet environment variables directly on the production server or container without committing to code.
CHardcode sensitive values in the Flask app source code for simplicity.
DUse Flask's config.from_pyfile() with a config file containing secrets committed to repo.
Attempts:
2 left
💡 Hint

Think about security and version control exposure.

Practice

(1/5)
1. What is the main reason to use environment variables in a Flask application?
easy
A. To make the app run without Python installed
B. To speed up the Flask server startup
C. To store user session data permanently
D. To keep sensitive information like passwords out of the code

Solution

  1. Step 1: Understand environment variables purpose

    Environment variables store sensitive info like passwords or API keys outside the code to keep them safe.
  2. Step 2: Identify the correct use in Flask

    Flask apps use environment variables to avoid hardcoding secrets and to configure settings per environment.
  3. Final Answer:

    To keep sensitive information like passwords out of the code -> Option D
  4. Quick Check:

    Environment variables = keep secrets safe [OK]
Hint: Environment variables protect secrets outside code [OK]
Common Mistakes:
  • Thinking environment variables speed up the app
  • Confusing environment variables with session storage
  • Believing environment variables remove Python dependency
2. Which of the following is the correct way to read an environment variable named SECRET_KEY with a default fallback in Flask?
easy
A. os.getenv('SECRET_KEY', 'default_key')
B. os.environ['SECRET_KEY', 'default_key']
C. os.get('SECRET_KEY', 'default_key')
D. os.environ['SECRET_KEY'] or 'default_key'

Solution

  1. Step 1: Recall correct function to get env variable with default

    Use os.getenv with two arguments: variable name and default value.
  2. Step 2: Check each option syntax

    A raises KeyError if missing despite the fallback attempt. B uses invalid tuple syntax for dict access. C uses non-existent os.get. D: os.getenv('SECRET_KEY', 'default_key') is correct.
  3. Final Answer:

    os.getenv('SECRET_KEY', 'default_key') -> Option A
  4. Quick Check:

    Use os.getenv with default [OK]
Hint: Use os.getenv('VAR', 'default') to read env vars safely [OK]
Common Mistakes:
  • Using os.environ['KEY'] or default which still raises KeyError if missing
  • Using non-existent os.get function
  • Using invalid tuple syntax with os.environ
3. Given this Flask code snippet:
import os
secret = os.getenv('MY_SECRET', 'none')
print(secret)

If the environment variable MY_SECRET is not set, what will be printed?
medium
A. none
B. An error will occur because MY_SECRET is missing
C. None
D. '' (empty string)

Solution

  1. Step 1: Understand os.getenv behavior with default

    If the environment variable is missing, os.getenv returns the default value provided.
  2. Step 2: Check the default value in code

    The default is the string 'none', so it will print exactly 'none'.
  3. Final Answer:

    none -> Option A
  4. Quick Check:

    Missing env var returns default string [OK]
Hint: Missing env var prints default string given [OK]
Common Mistakes:
  • Expecting a runtime error if env var missing
  • Confusing string 'none' with Python None
  • Assuming empty string is default
4. What is wrong with this Flask code snippet for reading an environment variable?
import os
api_key = os.environ.get('API_KEY', 'default')
print(api_key)
medium
A. The code will raise a KeyError if API_KEY is missing
B. os.environ is a dictionary and does not have a get method
C. There is no error; the code works correctly
D. os.environ.get does not accept a default value argument

Solution

  1. Step 1: Check os.environ type and methods

    os.environ behaves like a dictionary and supports the get method with a default value.
  2. Step 2: Verify code behavior if variable missing

    If 'API_KEY' is missing, get returns the default 'default' without error.
  3. Final Answer:

    There is no error; the code works correctly -> Option C
  4. Quick Check:

    os.environ.get supports default argument [OK]
Hint: os.environ.get('VAR', default) works like dict.get [OK]
Common Mistakes:
  • Thinking os.environ lacks get method
  • Expecting KeyError when using get with default
  • Confusing os.getenv and os.environ.get differences
5. You want to configure your Flask app to use different database URLs for development and production using environment variables. Which approach correctly achieves this?
hard
A. Hardcode the production URL in code and ignore environment variables
B. Set DATABASE_URL in environment for each environment, then use os.getenv('DATABASE_URL') in Flask config
C. Use os.environ['DATABASE_URL'] without setting it in the environment
D. Store URLs in a Python file and import them instead of environment variables

Solution

  1. Step 1: Understand environment variable usage for config

    Set environment variables differently on each machine (dev, prod) to hold the database URL.
  2. Step 2: Use os.getenv in Flask config to read the variable

    Using os.getenv('DATABASE_URL') reads the correct URL depending on environment.
  3. Final Answer:

    Set DATABASE_URL in environment for each environment, then use os.getenv('DATABASE_URL') in Flask config -> Option B
  4. Quick Check:

    Env vars per environment + os.getenv = config flexibility [OK]
Hint: Set env vars per environment, read with os.getenv [OK]
Common Mistakes:
  • Hardcoding URLs loses flexibility and security
  • Using os.environ without setting env var causes errors
  • Storing secrets in code files risks exposure
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard