Async SQLAlchemy会话:使用AsyncSession()或AsyncSession提交?

2024-04-18 15:11:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始在asyncio应用程序中使用来自sqlalchemyAsyncSession。但是,当将AsyncSession对象分配给下面的Foobased 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

Tags: thefromimportselfasyncioasyncobjectfoo