我开始在asyncio
应用程序中使用来自sqlalchemy
的AsyncSession
。但是,当将AsyncSession
对象分配给下面的Foo
(based on official docs)和Bar
类时,以下两种方法有什么区别吗
from asyncio import current_task
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import async_scoped_session
from sqlalchemy.ext.asyncio import AsyncSession
async_session_factory = sessionmaker(some_async_engine, class_=_AsyncSession)
AsyncSession = async_scoped_session(async_session_factory, scopefunc=current_task)
class Foo:
# https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html#using-asyncio-scoped-session
async def start(self):
self.async_session = AsyncSession()
async def some_function(self, some_object):
# use the AsyncSession directly
self.async_session.add(some_object)
# use the AsyncSession via the context-local proxy
await AsyncSession.commit()
# "remove" the current proxied AsyncSession for the local context
await AsyncSession.remove()
class Bar:
async def start(self):
self.async_session = AsyncSession()
async def some_function(self, some_object):
self.async_session.add(some_object)
await self.async_session.commit()
我在其他地方使用类似于Bar
的方法,并不断得到错误
sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlalchemy.dialects.postgresql.asyncpg.IntegrityError) <class 'asyncpg.exceptions.UniqueViolationError'>: duplicate key value violates unique constraint "scores_pkey"
当我尝试Foo
时,我得到了错误:
await AsyncSession.remove()
TypeError: object NoneType can't be used in 'await' expression
目前没有回答
相关问题 更多 >
编程相关推荐