异步sqlalchemy会话:使用asyncsession()或asyncsession提交?

sq1bmfud  于 2021-09-08  发布在  Java
关注(0)|答案(0)|浏览(677)

我开始使用 AsyncSession 从…起 sqlalchemy 在一个 asyncio 应用程序。但是,在分配 AsyncSession 对象类,如 Foo (基于官方文件)和 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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题