Flask 3 cheatsheet
Flask 3: Blueprints, database and CORS
5 common Flask 3 tasks.
Group routes in a blueprint
Split a large app into modules and register them with the app.
# users.py
bp = Blueprint("users", __name__, url_prefix="/users")
@bp.get("/")
def list_users():
return []
# app.py
app.register_blueprint(bp)
Use an application factory
Create the app in a function, which makes testing and configuration easier.
def create_app():
app = Flask(__name__)
app.config.from_prefixed_env()
app.register_blueprint(bp)
return app
Add SQLAlchemy
Install the extension and bind it to the app.
pip install flask-sqlalchemy
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db"
db.init_app(app)
Manage migrations
Create and apply database migrations with Flask-Migrate.
pip install flask-migrate
flask --app app db init
flask --app app db migrate -m "Add users"
flask --app app db upgrade
Allow cross-origin requests
Let a browser app on another origin call your API.
pip install flask-cors
from flask_cors import CORS
CORS(app, origins=["https://app.example.com"])