What's the recommended scoped_session usage pattern in a multithreaded sqlalchemy webapp?

后端 未结 2 1507
情歌与酒
情歌与酒 2021-01-31 17:30

I\'m writing an application with python and sqlalchemy-0.7. It starts by initializing the sqlalchemy orm (using declarative) and then it starts a multithreaded web server - I\'m

2条回答
  •  猫巷女王i
    2021-01-31 18:00

    Yes, this is the right way.

    Example:

    The Flask microframework with Flask-sqlalchemy extension does what you described. It also does .remove() automatically at the end of each HTTP request ("view" functions), so the session is released by the current thread. Calling just .commit() is not sufficient, you should use .remove().

    When not using Flask views, I usually use a "with" statement:

    @contextmanager
    def get_db_session():
        try:
            yield session
        finally:
            session.remove()
    
    with get_db_session() as session:
        # do something with session
    

    You can create a similar decorator.

    Scoped session creates a DBMS connection pool, so this approach will be faster than opening/closing session at each HTTP request. It also works nice with greenlets (gevent or eventlet).

提交回复
热议问题