Flask applications rely on configuration settings to manage database connections, security options, session behavior, file uploads, and debugging features. Flask provides a flexible configuration system that allows settings to be defined directly in code, loaded from external files, or managed through environment variables.
Syntax
1. The simplest way to configure a Flask app is by directly assigning values to app.config:
app.config['CONFIG_NAME'] = 'value'
Parameters:
- CONFIG_NAME: The name of the setting we want to define. Flask has built-in keys like DEBUG, SECRET_KEY and SQLALCHEMY_DATABASE_URI, but we can also create custom ones.
- value: The actual setting, which can be a string, boolean, integer or even a dictionary.
2. Alternatively, Flask allows configurations to be loaded from an external file, such as config.py:
app.config.from_pyfile('config.py')
This approach helps keep configuration settings separate from the main application logic, making the code more organized and maintainable.
Custom Configuration Variables
Besides built-in configuration options, Flask supports custom configuration variables for storing application-specific settings. This helps centralize configurable values and reduces the need to hardcode them throughout the application.
app.config['COMPANY_NAME'] = 'GeeksforGeeks'
app.config['ITEMS_PER_PAGE'] = 20
These values can be accessed anywhere in the application using:
app.config['COMPANY_NAME']
app.config.get('ITEMS_PER_PAGE')
Common Flask Configurations
Configuration in Flask refers to setting up parameters that control various aspects of the application. These include:
- Security settings : such as secret keys and session handling.
- Database settings : to connect and manage databases.
- Debugging options : to enable automatic reloading and error reporting.
- Session management : for handling user sessions.
- File handling & uploads : configuring file storage.
Let's look at some most common app configurations in Flask one by one.
Setting Up a Secret Key
A secret key is crucial for security-related functions in Flask, such as protecting session cookies and securing form submissions.
app.config['SECRET_KEY'] = 'your_secret_key'
This key should always be kept private and unique. In a production environment, it’s recommended to store it in an environment variable instead of hardcoding it in the script.
Configuring a Database
Most Flask applications require a database. Flask supports SQLAlchemy for database management and we configure it using:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
- The SQLALCHEMY_DATABASE_URI defines the database type and location. Here, we’re using an SQLite database stored in a file named database.db.
- The SQLALCHEMY_TRACK_MODIFICATIONS setting is set to False to improve performance by disabling tracking of modifications to objects.
If you're using a different database, such as PostgreSQL or MySQL, the URI changes accordingly:
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:password@localhost/db_name'
Session Management Configuration
Flask provides session management to store user-related information across multiple requests. The default session type stores data in cookies, but we can configure it for better security and control:
from datetime import timedelta
app.config['SESSION_TYPE'] = 'filesystem'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=1)
- The SESSION_TYPE is set to filesystem, meaning session data will be stored on the server’s file system instead of client-side cookies.
- The PERMANENT_SESSION_LIFETIME sets how long a session remains active before expiring. Here, it’s set to 1 day.
Configuring JSON Responses
Flask returns JSON responses for APIs and we can configure how JSON data is handled using:
app.config['JSON_SORT_KEYS'] = False
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
- JSON_SORT_KEYS = False prevents automatic sorting of keys in JSON responses, preserving the order in which data is added.
- JSONIFY_PRETTYPRINT_REGULAR = True ensures the JSON output is formatted in a human-readable way.
Loading Configurations from a File
Instead of setting configurations inside app.py, we can store them in a separate configuration file named config.py:
# config.py
SECRET_KEY = 'your_secret_key'
SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db'
DEBUG = True
Then we load it into Flask app using:
app.config.from_pyfile('config.py')
Configuration Loading Priority
Flask applies configuration settings in the order they are loaded. If the same configuration key is defined multiple times, the most recently loaded value overrides the previous one.
app.config['DEBUG'] = False
app.config.from_pyfile('config.py')
app.config.from_envvar('APP_CONFIG')
Explanation: Here, values loaded from APP_CONFIG will override any matching settings from config.py, and values from config.py will override those defined directly in the application.
Environment-Specific Configurations
Flask supports different configurations for development, testing and production environments. We can define different settings and load them dynamically based on the environment.
For example, using from_object():
import os
env = os.getenv('FLASK_ENV', 'development')
if env == 'development':
app.config.from_object('config.DevelopmentConfig')
elif env == 'production':
app.config.from_object('config.ProductionConfig')
And define different settings in config.py:
class Config:
SECRET_KEY = 'your_secret_key'
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///dev.db'
class ProductionConfig(Config):
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'mysql://user:password@localhost/prod_db'
This approach allows Flask to load different configurations based on whether the app is running in development or production.
Environment specific Configuration is covered in more detail in a separate article, click here to read it.
Enabling Debug Mode
During development, enabling debug mode helps catch errors quickly by allowing automatic reloading of the server and displaying detailed error messages.
app.config['DEBUG'] = True
With DEBUG = True, Flask will automatically restart when it detects changes in the code, which is useful for development but should never be enabled in production.
File Upload Configurations
If our application allows users to upload files, we must specify a folder to store these files:
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB limit
- The UPLOAD_FOLDER specifies where uploaded files will be stored.
- The MAX_CONTENT_LENGTH limits the file upload size (here, 16MB). This prevents users from uploading excessively large files.