首页 > 解决方案 > 异步 SQLAlchemy 会话:使用 AsyncSession() 或 AsyncSession 提交?

问题描述

我开始在应用AsyncSession程序中使用。但是,在将对象分配给(基于官方文档)及以下类时,以下两种方式之间有什么区别吗?sqlalchemyasyncioAsyncSessionFooBar

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

标签: pythonpython-3.xasynchronoussqlalchemypython-asyncio

解决方案


推荐阅读