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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Support Vector Machine (SVM) Algorithm Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read