PostgreSQL 未填充异步(FastAPI)

问题描述 投票:0回答:1

我对 FastAPI 比较陌生,我正在尝试创建一个类,该类具有单个表,一旦服务器开始使用,该表就会填充数据:

uvicorn main:app --reload

我一直在努力使其工作并连续几个小时进行故障排除,但此时我真的很感激一些建议。

这是我到目前为止的代码:

from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import List, Annotated
from sqlalchemy.orm import Session
from sqlalchemy import Column, Integer, String, text
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base
from contextlib import asynccontextmanager

DATABASE_URL = "postgresql+asyncpg://$DB_USER:$DB_PWD@$DB_SERVER/$DB_NAME"

Base = declarative_base()

class Person(Base):
    __tablename__ = "persons"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    age = Column(Integer)
    
engine = create_async_engine(DATABASE_URL, future=True, echo=True)

SessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)

app = FastAPI()
@asynccontextmanager
async def lifespan(app: FastAPI):
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
        await seed_database(conn)
    
    yield 
    await engine.dispose()

app.lifespan_context = lifespan

async def seed_database(conn):
    await conn.execute(text("INSERT INTO persons (name, age) VALUES ('Alice', 23)"))
    await conn.execute(text("INSERT INTO persons (name, age) VALUES ('Bob', 22)"))
    await conn.commit()
    print("Database seeded with initial persons.")

@app.get("/")
async def read_root(db: AsyncSession = Depends(lambda: SessionLocal())):
    result = await db.execute(text("SELECT * FROM persons"))
    persons = result.mappings().all()
    return {"persons": persons}

我尝试切换代码并执行一些解决方法,但由于某种原因我无法让它工作..

python postgresql fastapi
1个回答
0
投票

您在 Depends() 中使用 SessionLocal(),它们不是为异步会话设计的。尝试如下操作:

async def get_db():
    async with SessionLocal() as session:
        yield session

async def read_root(db: AsyncSession = Depends(get_db)):
© www.soinside.com 2019 - 2024. All rights reserved.