Flask App Configuation
Flask application often needs configuration for various settings to ensure that it functions correctly. These settings manage aspects such as database connections, security, session handling and more. Flask provides a simple way to manage configurations using the app.config dictionary.
We can define these settings directly in our code, load them from a file or even set them based on the environment (development, testing, production). In this article, we’ll explore how to configure a Flask app, understand the syntax and look at the most commonly used configuration settings.
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.
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:
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 lod it into Flask app using:
app.config.from_pyfile('config.py')
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():
if app.config['ENV'] == 'development':
app.config.from_object('config.DevelopmentConfig')
elif app.config['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.