首页 > 解决方案 > '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

标签: pythonsqlalchemyfastapi

解决方案


我已经弄清楚了,基本上,当您将生成器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

这是一个很小的细节,可能会妨碍一些初学者(比如我)。因此,请更仔细地查看您的代码。


推荐阅读