Skip to content
Myr

Switch to teardown_appcontext for docs in sqlalchemy pattern

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 94c6ae5 · Browse files · 1 file+6 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+6 added−4 removed

  • other:+6 added−4 removed

1 file+6 added−4 removed

modified:docs/patterns/sqlalchemy.rst+6 added-4 removed
59 unmodified lines
60already with the :class:`~sqlalchemy.orm.scoped_session`.6162To use SQLAlchemy in a declarative way with your application, you just63have to put the following code into your application module. Flask will64automatically remove database sessions at the end of the request for you::64automatically remove database sessions at the end of the request or65when the application shuts down::6667 from yourapplication.database import db_session6868 @app.teardown_request69 @app.teardown_appcontext70 def shutdown_session(exception=None):71 db_session.remove()7273Here is an example model (put this into `models.py`, e.g.)::
61 unmodified lines
135 def init_db():136 metadata.create_all(bind=engine)137138As for the declarative approach you need to close the session after138each request. Put this into your application module::139each request or application context shutdown. Put this into your140application module::141142 from yourapplication.database import db_session143142 @app.teardown_request144 @app.teardown_appcontext145 def shutdown_session(exception=None):146 db_session.remove()147148Here is an example table and model (put this into `models.py`)::
68 unmodified lines