Correct usage of sqlalchemy scoped_session with py

2019-07-18 01:23发布

I'm building an app using asyncio. I will be using sqlalchemy as the orm. From what i understand scoped_session associates a session with a thread so they don't with each other's operations. Now since asyncio works on a single thread and I believe scoped_session will not work correctly which will cause problems. What would be the correct way to use sqlalchemy sessions with asyncio?

2条回答
Juvenile、少年°
2楼-- · 2019-07-18 01:38

The answer depends on your code.

In general you can use sessionmaker for creating session factory and using it on your own.

If your code has implicit context you may use scoped_session with custom scopefunc as shown in example.

Implicit context may utilize asyncio.Task.current_task() call but you need to find a way for scoped session destruction also.

查看更多
再贱就再见
3楼-- · 2019-07-18 01:50

I don't think you can use sqlalchemy with asyncio. The SQL Alchemy API is all blocking and incompatible with asyncio. http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and-databases/

You can use SQL Alchemy asynchronously with gevent though, as long as you can find a gevent-compatible driver for your database. And gevent greenlents map nicely to scoped_session.

EDIT: actually, it looks like you can use SQL Alchemy with asyncio as long as you can find an asyncio-compatible driver for your database, such as https://github.com/aio-libs/aiopg . As for scoped_session, use current_task and destroy it on your web framework's request end.

查看更多
登录 后发表回答