python - 'async_generator 不是可调用对象' FastAPI 依赖问题应用程序
问题描述
我正在尝试创建一个 FastAPI 和异步 sqlalchemy。
get_db 依赖会导致一个奇怪的TypeError: <async_generator object get_db at 0x7ff6d9d9aa60> is not a callable object
问题。
这是我的代码:
数据库.py
from typing import Generator
from .db.session import SessionLocal
async def get_db() -> Generator:
try:
db = SessionLocal()
yield db
finally:
await db.close()
会话.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from .core.config import settings
engine = create_async_engine(
settings.SQLALCHEMY_DATABASE_URI,
pool_pre_ping=True
)
SessionLocal = AsyncSession(
autocommit=False,
autoflush=False,
bind=engine
)
我几乎遵循了此处发布的说明:https ://6060ff4ffd0e7c1b62baa6c7--fastapi.netlify.app/advanced/sql-databases-sqlalchemy/#more-info
解决方案
我已经弄清楚了,基本上,当您将生成器get_db()
称为 FastAPI 端点的依赖项时,您基本上只是将其称为get_db
没有括号。
例如:
from typing import List, Any
from fastapi import APIRouter, HTTPException, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession
from . import models, crud, schemas
from .deps.db import get_db
router = APIRouter()
@router.post('/',
response_model=schemas.StaffAccount,
status_code=status.HTTP_201_CREATED)
async def create_staff_account(
db: AsyncSession = Depends(get_db),
staff_acct: schemas.StaffAccountCreate = Depends(schemas.StaffAccountCreate)
) -> Any:
q = await crud.staff.create(db=db, obj_in=staff_acct)
if not q:
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='An error occurred while processing your request')
return q
这是一个很小的细节,可能会妨碍一些初学者(比如我)。因此,请更仔细地查看您的代码。
推荐阅读
- html - 当图像在容器内缩小时,填充底部黑客不起作用
- sql - 嵌套查询中的 SQL where 子句与嵌套查询中不存在的列
- angular - Angular 8 Observable.interval 改变了吗?
- hla - OpenRTI 回调的问题
- chisel - 在 Chisel 中循环循环缓冲区
- node.js - 使用 Content-Transfer-Encoding 的消息编码错误:二进制
- python - 在 Python 中生成具有指定边际的 copula 相关样本
- android - java.lang.NullPointerException 当 dataBinding 启用 = true
- ios - 在 Xamarin 应用程序中获取最新的 Apple 支付交易
- java - 如何在arraylist中找到前20个最常用的词