我陷入了aiopg的问题。当我与引擎异步并尝试将结果返回到 FastApi 中的端点时,存在一个问题。在下面查看我的 db 类。
class DBEngine:
def __init__(self, connection_url: str) -> None:
self.dsn = connection_url
self.engine: Optional[Engine] = None
async def connect(self) -> None:
self.engine = await create_engine(dsn=self.dsn, maxsize=100)
@property
def client(self) -> Engine:
if self.engine:
return self.engine
raise Exception("Not connected to database")
async def close(self) -> None:
if self.engine:
self.engine.close()
await self.engine.wait_closed()
如您所见,有一个属性,我在模型类的方法代码中使用它:
class Products(Base):
__tablename__ = "products"
UUID = sa.Column(
UUID(as_uuid=True),
primary_key=True,
default=uuid.uuid4,
unique=True,
nullable=False,
)
product_name = sa.Column(sa.String())
@classmethod
async def create_loan(
cls,
*,
product_name: str
) -> "Products":
query = cls.insert_query(
product_name=product_name
)
async with db_engine.client.acquire() as conn:
cursor = await conn.execute(query)
return await cursor.fetchone()
最后我将在 fastapi 中显示一个端点:
@routes.post("/api/v1/loans")
async def create_loan(loan: Loan):
product = await Products.create_loan(product_name=loan.product_name)
return {"loan_id": product.UUID}
错误日志:
**Traceback**
...
aiopg.sa.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically.
请告诉我出了什么问题,我花了很多时间来解决这个问题。欢迎回答,谢谢。