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.
Python
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:
Python
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:
Python
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:
Python
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:
Python
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:
Python
# config.py
SECRET_KEY = 'your_secret_key'
SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db'
DEBUG = True
Then we lod it into Flask app using:
Python
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():
Python
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:
Python
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.
Python
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:
Python
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.
Similar Reads
Python Pyramid - Application Configuration Pyramid is a lightweight and flexible Python web framework designed to build web applications quickly and easily. One of the key strengths of Pyramid is its configurability, allowing developers to tailor the framework to suit the specific needs of their application. In this article, we'll explore th
4 min read
How to Run a Flask Application After successfully creating a Flask app, we can run it on the development server using the Flask CLI or by running the Python script. Simply execute one of the following commands in the terminal:flask --app app_name runpython app_nameFile StructureHere, we are using the following folder and file.Dem
4 min read
FastAPI - Mounting Flask App A modern framework in Python that is used for building APIs is called FastAPI while a micro web framework written in Python that is used for developing web applications is called Flask. The FastAPI and Flask provide different features. Sometimes, it becomes crucial to use features of both in a singl
2 min read
Flask Environment Specific Configurations When developing a Flask application, different environments such as development, testing, and production require different settings. For example, in development, we may want debugging enabled, while in production, we need stricter security settings. Flask allows us to configure our application based
3 min read
Flask - Language Detector App In this article, we will see how we can detect the language of an entered text in Python using Flask. To detect language using Python we need to install an external library called "langdetect" and "pycountry". Let's see how to implement Flask Language Detector App, before implementation we will try
4 min read