python - 异步 SQLAlchemy 会话:使用 AsyncSession() 或 AsyncSession 提交?
问题描述
我开始在应用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
解决方案
推荐阅读
- android - 如何从 Retrofit 调用 dotnet api?
- angular6 - angular6中的aws s3存储桶图像上传有问题
- sql - sql 在但有多个列
- mysql - MySQL中有没有类似substr_replace的东西?
- ruby-on-rails - 如何在 ruby 中使用 CustomHealthCheck 和 health_check gem?
- reactjs - React-admin 选项卡名称翻译
- c# - C# 控制台自动换行
- reactjs - 指定时,package.json 中的“代理”必须是字符串
- c# - C#发现TCP客户端消失
- laravel-5.7 - 使用 laravel 5.7 的路线编辑、显示和删除不起作用