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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
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 customscopefunc
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.
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
, usecurrent_task
and destroy it on your web framework's request end.