Skip to main content

Run Code Before the First Request in Flask

To run some code (once) before the first request in a Flask app, you could use the before_first_request decorator. However, since it's deprecation in Flask 2.3.0.

The recommended way is to use it after app config by manually pushing the app context, like so:

app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


def create_app():
app = Flask(__name__)

# Configure the app
app.config.from_object('your_config_module')

# Initialize extensions
db.init_app(app)

# Run some custom startup code
with app.app_context():
# This code runs once the application context is available
print("Running startup tasks...")
# Example: create tables if not already present
db.create_all()

# Register blueprints
# from .routes import main
# app.register_blueprint(main)

return app
info

This example is using the app factory pattern. If you're using the app object directly, you can run the code after app creation.