Proper use of sqlalchemy scoped_session with python asyncio

I am creating an application using asyncio. I will use sqlalchemy as orm. From what I understand, scoped_session associates a session with a thread, so they do not perform operations with each other. Now, since asyncio is working on a single thread, and I believe that scoped_session will not work correctly, which will cause problems. What would be the correct way to use sqlalchemy sessions with asyncio?

+1
source share
2 answers

The answer depends on your code.

In general, you can use sessionmaker to create a factory session and use it yourself.

If your code has an implicit context, you can use scoped_session with a custom scopefunc , as shown in the example .

An implicit context may use the asyncio.Task.current_task () call , but you also need to find a way to destroy the restricted session.

+1
source

I do not think you can use sqlalchemy with asyncio. The Alchemy SQL API is completely blocked and incompatible with asyncio. http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and-databases/

You can use Alchemy SQL asynchronously with gevent , although you can find a gevent-compatible driver for your database. And gentent greenlents paint beautifully before scoped_session .

EDIT: in fact, it looks like you can use SQL Alchemy with asyncio if you can find an asyncio-compatible driver for your database, for example https://github.com/aio-libs/aiopg . As for scoped_session , use current_task and destroy it at the end of the web frame request.

0
source

Source: https://habr.com/ru/post/1013072/


All Articles