Flask App Configuation (original) (raw)

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:

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.

Python `

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:

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

`

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 `

from datetime import timedelta app.config['SESSION_TYPE'] = 'filesystem' app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=1)

`

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

`

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 load it into Flask app using:

Python `

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.

Python `

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():

Python `

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:

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

`