Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 72 ยท Structure and Configuration

Configuration and Environments

Configure Flask the right way: app.config, config classes, from_object, from_prefixed_env, the instance folder, secret keys and twelve-factor style environments.

Every real application behaves differently depending on where it runs. On your laptop you want debug pages and a throwaway SQLite file. In tests you want a clean in-memory database. In production you want a real database, a long random secret key and no debugger. The code is the same; only the configuration changes.

Flask keeps configuration in one place, app.config, and gives you several ways to fill it. This lesson covers the dictionary itself, config classes, environment variables, the instance folder for files that must not live in Git, how to treat secrets, and how to fail early when something is missing.

app.config is a dictionary

app.config is a dictionary subclass. You read and write it with ordinary item access, and Flask itself, as well as extensions, look up their settings in it. A fresh app already holds many built-in keys with defaults:

Key Meaning
DEBUG Debug mode: reloader and interactive debugger (never in production)
TESTING Testing mode: exceptions propagate to the test client
SECRET_KEY Signs sessions and other cookies; None until you set it
SESSION_COOKIE_SECURE Send the session cookie only over HTTPS
PERMANENT_SESSION_LIFETIME How long a permanent session lasts
MAX_CONTENT_LENGTH Largest request body accepted; None means no limit
SERVER_NAME Host (and port) used when building URLs outside a request

Extensions add their own, such as SQLALCHEMY_DATABASE_URI. Your own settings live in the same dictionary, so choose names that cannot collide with theirs.

Python Reading, setting and loading config

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The core ideas:

  • Item access and update() work as on any dict. Use app.config.get("KEY", default) when a setting is optional. A plain app.config["KEY"] raises KeyError when it is missing, which is often what you want for required settings.
  • from_object() copies every UPPERCASE attribute of a class, module or import path string into the config. That is why debug_note never appears. Classes support inheritance, so DevelopmentConfig only lists what differs from Config.
  • from_mapping() is the same for a dictionary or keyword arguments.
  • Settings are read when they are used, but several (such as the secret key and cookie options) are read on each request, while others are read once at startup. Set everything inside the factory, before you register extensions that read it.

You can pass a dotted string to from_object, for example app.config.from_object("myapp.config.ProductionConfig"). Flask imports it for you. This makes it easy to choose the class by name from an environment variable.

Layering: from defaults to overrides

Good configuration is built in layers. Each layer overrides the one below it, so the later a source is applied, the higher its priority.

flowchart BT
    A["1. Defaults in code<br/>(Config class, safe values)"] --> B["2. Environment class<br/>(Development / Production)"]
    B --> C["3. Instance file<br/>(this server's values)"]
    C --> D["4. Environment variables<br/>(from_prefixed_env)"]
    D --> E["5. Explicit overrides<br/>(tests, create_app argument)"]

Apply layers from the bottom up: each step may replace values from the steps before it.

You do not need all five layers in every project. A common minimal setup is defaults in code, then environment variables, then test overrides. The sections below show each source.

Environment variables with from_prefixed_env

Environment variables are the standard way to hand settings to a program without touching its files. Flask 2.1 added app.config.from_prefixed_env(prefix). It reads every variable that begins with PREFIX_ (the default prefix is FLASK), strips the prefix and puts the rest into the config.

Values are parsed as JSON when they can be, so "25" becomes the integer 25, "true" becomes True and '["ada", "grace"]' becomes a list. Anything that is not valid JSON stays a string. A double underscore means nesting: MYAPP_DATABASE__HOST sets the key HOST inside the dictionary DATABASE.

Python from_prefixed_env: types and nesting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details to remember. First, nested keys merge into an existing dictionary: DATABASE kept its name and gained HOST and PORT. Second, the last two lines show the trap of JSON parsing: FLASK_TESTING=1 produces the integer 1, not True. It is truthy, so most code works, but prefer true/false in environment files when you can. A value that looks like JSON but must stay a string, such as a numeric password, needs converting in your code.

The prefix FLASK_ also has a role beyond config: the flask command itself reads variables such as FLASK_DEBUG and FLASK_APP. Using a prefix of your own (BOOKS_, MYAPP_) keeps your settings visibly separate.

There is also app.config.from_envvar("APP_SETTINGS"). It does something different: the environment variable holds the path of a config file, which Flask then loads.

The instance folder

Some settings should not be committed to Git: the secret key, database passwords, API tokens, a path that exists only on one machine. Flask has a convention for this, the instance folder, a directory next to your package (by default instance/) that holds files specific to one deployment. You add it to .gitignore.

Turn it on with instance_relative_config=True; then relative file names in from_pyfile() and from_file() are looked up inside the instance folder rather than next to your code. Below, a temporary folder plays the role of instance/, and we load a Python file and a TOML file from it.

Python Loading settings from instance files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The pattern in a real factory is:

Python
app = Flask(__name__, instance_relative_config=True)
app.config.from_object("myapp.config.Default")
app.config.from_pyfile("config.py", silent=True)   # optional, per-machine

Passing silent=True makes the file optional, so development works without it while production provides it. Flask works out the default instance_path for you; you can print app.instance_path to see where it is. from_file() accepts any loader, so json.load (in text mode) or tomllib.load (binary mode, hence text=False) work. Only top-level UPPERCASE keys are imported, which is why [MAIL] became a dictionary under the key MAIL.

Handling secrets

The most important setting is SECRET_KEY. Flask uses it to sign the session cookie (and other signed data), so anyone who knows it can forge a cookie that says "I am user 1". It must be long, random and private.

Terminal
python -c "import secrets; print(secrets.token_hex(32))"

Rules of thumb:

  • Never commit secrets. A key in a Git repository is compromised, even in a private one and even after you delete it, because history remembers. If one leaks, rotate it.
  • Use a harmless dummy default for development only (like "dev"), and make production refuse to start without a real value.
  • Prefer environment variables or the instance folder to hold production secrets, or the secret store of your hosting platform.
  • Do not print secrets into logs or error pages. When you must show one, mask most of it.
  • Rotating the key logs everybody out, since old signatures stop validating. Plan for that.

python-dotenv is a popular helper: if it is installed, the flask command automatically loads variables from a .env file and a .flaskenv file in the project folder. Put non-secret defaults such as FLASK_DEBUG=1 in .flaskenv (safe to commit) and secrets in .env (listed in .gitignore). This convenience applies to the CLI, not to a production WSGI server, which gets its variables from the process environment or its service definition.

Twelve-factor thinking

The "twelve-factor app" manifesto gives a simple rule for config: keep it in the environment, strictly separate from code. The same build, whether a container image or a checkout, must run in development, staging and production, with only its environment variables differing.

flowchart LR
    CODE["Same code<br/>(one build)"] --> DEV["development<br/>FLASK_DEBUG=1<br/>SQLite file"]
    CODE --> STG["staging<br/>staging database"]
    CODE --> PRD["production<br/>real secrets<br/>real database"]

One codebase, many deployments. What differs is injected from outside.

In practice this means the code contains defaults and structure (which settings exist, what type they are) while values for secrets and for anything environment-specific arrive from outside. Avoid if hostname == "prod-1" branches and avoid separate code branches per environment: both make it impossible to be sure that what you tested is what you run.

Failing fast

A missing setting should stop the app at startup, not surface as a confusing error three hours later when a user first hits the code path that needs it. Validate the config inside the factory and raise a clear error. The example below combines layers (defaults, environment class, prefixed variables, explicit overrides) with validation and a masked secret.

Python Layered config with fail-fast validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In step 2 the production check reported only SECRET_KEY as missing, because DATABASE_URL had a default. That default is exactly the kind of dangerous convenience the second check catches: production starting against a SQLite development file. A boot-time failure costs a minute of your time; the same mistake found by users costs far more.

Never leave DEBUG = True on a public server. The interactive debugger lets anyone who can reach it run Python code on your machine. Production should also set SESSION_COOKIE_SECURE = True so the session cookie is never sent over plain HTTP. See Web Security Essentials.

Common mistakes

  • Lowercase setting names. from_object and from_file only import UPPERCASE names; a lowercase one is silently skipped.
  • Reading config too early. Using current_app.config at import time fails (no app yet). Read it inside views, functions called at request time, or the factory.
  • Committing .env or instance/. Add both to .gitignore before the first commit.
  • A weak or default secret key in production. "dev" and "change-me" are the first strings an attacker tries.
  • Environment values are strings. With from_prefixed_env simple JSON values are converted for you; with plain os.environ.get(...) you must convert numbers and booleans yourself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A config class defines DEBUG = True and site_name = 'Shelf'. After app.config.from_object(MyConfig), which settings are in app.config?

    from_object imports only attributes whose names are all uppercase. Lowercase attributes are ignored.
  2. 2. With app.config.from_prefixed_env('MYAPP'), what does the variable MYAPP_DATABASE__PORT=5432 produce?

    The prefix is stripped, a double underscore means nesting, and the value is parsed as JSON, so 5432 becomes an int.
  3. 3. Why is the instance folder a good place for SECRET_KEY on a production server?

    The instance folder is meant for per-machine files that must not be committed. Its security comes from not being in the repository, not from any special protection.
  4. 4. What is the main point of the twelve-factor rule 'store config in the environment'?

    Separating config from code lets you deploy exactly what you tested, with different settings per environment.
  5. 5. A required setting is missing in production. What is the best behaviour?

    Failing fast at startup surfaces the problem immediately and prevents a half-configured app from serving traffic.

Summary

  • app.config is a dict of settings; Flask, extensions and your code all read from it.
  • Load settings with from_object (UPPERCASE attributes), from_mapping, from_prefixed_env (JSON-parsed values, __ for nesting), from_pyfile and from_file.
  • Build config in layers: defaults, environment class, instance file, environment variables, explicit overrides.
  • Keep per-machine and secret values out of Git: instance folder, .env, or your platform's secret store.
  • Use a long random SECRET_KEY, never DEBUG=True in production, and validate required settings at startup.
  • Twelve-factor style: one build, configuration injected from the environment.

Next: Hooks, Application Context and g, running code before and after every request.