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

后端 未结 2 1503
情歌与酒
情歌与酒 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条回答
  • 2021-01-31 17:58

    You don't need to create a scoped session if you create new session for each request and each request is handled by single thread.

    You have to call s.commit() to make pending objects persistent, i.e. to save changes into database.

    You may also want to close session by calling s.close().

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题