0
0
FlaskHow-ToBeginner · 3 min read

How to Use Config from File in Flask: Simple Guide

In Flask, you can load configuration from a file using app.config.from_pyfile('filename.py'). This method reads Python file settings and applies them to your Flask app's configuration.
📐

Syntax

The main method to load config from a file in Flask is app.config.from_pyfile(filename). Here, filename is the path to a Python file containing configuration variables as uppercase keys.

  • app.config: The Flask app's configuration dictionary.
  • from_pyfile: Loads config from a Python file.
  • filename: The relative or absolute path to the config file.
python
app.config.from_pyfile('config.py')
💻

Example

This example shows how to create a config file and load it into a Flask app. The config file sets a secret key and debug mode.

python
from flask import Flask

app = Flask(__name__)

# Load config from file named 'config.py'
app.config.from_pyfile('config.py')

@app.route('/')
def home():
    secret = app.config['SECRET_KEY']
    debug = app.config['DEBUG']
    return f"Secret Key: {secret}, Debug Mode: {debug}"

if __name__ == '__main__':
    app.run()
Output
Running the app and visiting '/' shows: Secret Key: mysecret, Debug Mode: True
⚠️

Common Pitfalls

Common mistakes when loading config from a file include:

  • Using a config file with syntax errors or missing uppercase keys.
  • Not placing the config file in the correct directory or giving a wrong path.
  • Trying to load non-Python config files without converting them.
  • Forgetting to restart the Flask app after changing the config file.

Always ensure your config file is a valid Python file with uppercase variable names.

python
## Wrong way: config file with lowercase keys
# config.py
secret_key = 'wrong'
debug = False

## Right way: uppercase keys
# config.py
SECRET_KEY = 'correct'
DEBUG = True
📊

Quick Reference

Summary tips for using config files in Flask:

  • Config file must be a valid Python file.
  • Use uppercase variable names for config keys.
  • Use app.config.from_pyfile('filename.py') to load config.
  • Restart the app after config changes.
  • Access config values via app.config['KEY'].

Key Takeaways

Use app.config.from_pyfile('filename.py') to load config from a Python file in Flask.
Config keys must be uppercase variables inside the config file.
Place the config file in the correct path accessible by your Flask app.
Restart the Flask app after modifying the config file to apply changes.
Access config values with app.config['KEY'] in your Flask code.