Preparing a Flask application for production involves setting up secure and optimized configurations. This includes configuring a dedicated config.py
file for production settings and using environment variables to manage sensitive data securely.
In this article, we will go through the steps to prepare your Flask application for production with real examples.
config.py
FileFlask applications benefit from a centralized configuration file that separates development and production settings. Create a config.py
file in your project directory:
import os class Config: SECRET_KEY = os.environ.get('SECRET_KEY', 'default_secret_key') SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'sqlite:///default.db') DEBUG = False class DevelopmentConfig(Config): DEBUG = True class ProductionConfig(Config): DEBUG = False TESTING = False
In this example, we have defined a base Config
class and specific classes for development and production.
Update your Flask application to use the config.py
file:
from flask import Flask from config import DevelopmentConfig, ProductionConfig app = Flask(__name__) # Use the appropriate configuration based on the environment environment = os.environ.get('FLASK_ENV', 'development') if environment == 'production': app.config.from_object(ProductionConfig) else: app.config.from_object(DevelopmentConfig) @app.route('/') def home(): return "Welcome to the Flask App!"
This setup allows you to switch configurations based on the FLASK_ENV
environment variable.
Environment variables provide a secure way to manage sensitive data such as API keys, database URLs, and secret keys. Create a .env
file in your project:
SECRET_KEY=your_production_secret_key DATABASE_URL=postgresql://username:password@localhost/production_db FLASK_ENV=production
Use the python-dotenv
package to load these variables:
pip install python-dotenv
Update your application to load environment variables:
from dotenv import load_dotenv import os load_dotenv() app = Flask(__name__) app.config.from_object('config.ProductionConfig')
Set up logging for production to monitor your application's behavior:
import logging from logging.handlers import RotatingFileHandler if not app.debug: handler = RotatingFileHandler('error.log', maxBytes=10000, backupCount=3) handler.setLevel(logging.ERROR) app.logger.addHandler(handler)
This will log errors to a file named error.log
.
Use a production server like Gunicorn or uWSGI to deploy your Flask application. For example, install Gunicorn:
pip install gunicorn
Run your application with Gunicorn:
gunicorn -w 4 app:app
Here, -w 4
specifies 4 worker processes.
Ensure your application is served over HTTPS in production. Use services like Nginx or Apache to handle SSL/TLS certificates.
Preparing a Flask application for production involves configuring a config.py
file, using environment variables for sensitive data, and deploying the app on a production server. Following these steps ensures your application is secure, optimized, and ready for deployment.