|
| 1 | +""" |
| 2 | +https://github.com/dtheodor/flask-sqlalchemy-session is archived |
| 3 | +
|
| 4 | +Implements fixes to make it work with modern Werkzeug |
| 5 | +https://github.com/dtheodor/flask-sqlalchemy-session/pull/17 |
| 6 | +https://github.com/dtheodor/flask-sqlalchemy-session/pull/15 |
| 7 | +""" |
| 8 | + |
| 9 | +from flask import current_app |
| 10 | +from sqlalchemy.orm import scoped_session |
| 11 | +from werkzeug.local import LocalProxy |
| 12 | + |
| 13 | + |
| 14 | +def _get_session(): |
| 15 | + app = current_app._get_current_object() |
| 16 | + if not hasattr(app, "scoped_session"): |
| 17 | + raise AttributeError( |
| 18 | + "{} has no 'scoped_session' attribute. You need to initialize it " |
| 19 | + "with a flask_scoped_session.".format(app) |
| 20 | + ) |
| 21 | + return app.scoped_session |
| 22 | + |
| 23 | + |
| 24 | +current_session = LocalProxy(_get_session) |
| 25 | +"""Provides the current SQL Alchemy session within a request. |
| 26 | +
|
| 27 | +Will raise an exception if no :data:`~flask.current_app` is available or it has |
| 28 | +not been initialized with a :class:`flask_scoped_session` |
| 29 | +""" |
| 30 | + |
| 31 | + |
| 32 | +class flask_scoped_session(scoped_session): |
| 33 | + """A :class:`~sqlalchemy.orm.scoping.scoped_session` whose scope is set to |
| 34 | + the Flask application context. |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__(self, session_factory, app=None): |
| 38 | + """ |
| 39 | + :param session_factory: A callable that returns a |
| 40 | + :class:`~sqlalchemy.orm.session.Session` |
| 41 | + :param app: a :class:`~flask.Flask` application |
| 42 | + """ |
| 43 | + try: |
| 44 | + from greenlet import getcurrent as scopefunc |
| 45 | + except ImportError: |
| 46 | + from threading import get_ident as scopefunc |
| 47 | + super().__init__(session_factory, scopefunc=scopefunc) |
| 48 | + if app is not None: |
| 49 | + self.init_app(app) |
| 50 | + |
| 51 | + def init_app(self, app): |
| 52 | + """Setup scoped session creation and teardown for the passed ``app``. |
| 53 | +
|
| 54 | + :param app: a :class:`~flask.Flask` application |
| 55 | + """ |
| 56 | + app.scoped_session = self |
| 57 | + |
| 58 | + @app.teardown_appcontext |
| 59 | + def remove_scoped_session(*args, **kwargs): |
| 60 | + app.scoped_session.remove() |
0 commit comments