Python Flask SQLAlchemy context introductionlink

If you plan to use only one application, you can largely skip this article. Simply pass your application to the SQLAlchemy constructor and you’re set up. However, if you want to use more than one application, or if you want to create the application dynamically in the functionality to be read.

If you define an application in a function but in a SQLAlchemy global object, how does the latter know about the former? The answer is the init_app() function:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    return app

All it does is prepare the application SQLAlchemy to use. However, this does not now bind SQLAlchemy objects to your application. Why not do that? Because multiple applications may have been created.

So how does SQLAlchemy learn about your application? You will have to set an application context. This happens automatically if you do something in the Flask view function or in the CLI command. However, if you are working in an interactive shell, you will have to do it yourself (see Creating an application context).

If you try to perform a database operation outside of the application context, you will see the following error:

The application cannot be found. Work inside view functions or push application context.

In short, do the following:

>>> from yourapp import create_app
>>> app = create_app()
>>> app.app_context().push()

Alternatively, use the WITH statement to set and disassemble:

def my_function():
    with app.app_context():
        user = db.User(...)
        db.session.add(user)
        db.session.commit()

Some of the functions inside Flask-SQLAlchemy also have the option to accept an application in order to operate on it:

>>> from yourapp import db, create_app
>>> db.create_all(app=create_app())