Два варианта эндпоинта FastAPI, который дёргает БД и внешний сервис. Что
будет работать как ожидается?
middle
correct_vs_wrong
#19
Вариант 1
# БД синхронная psycopg, HTTP синхронный requests
@app.get("/orders/{id}")
async def get_order(id: int):
# ← async endpoint, но...
order = psycopg_conn.execute("SELECT ... WHERE id=%s", (id,)).fetchone()
shipping = requests.get(f"http://ship/{id}").json()
return {"order": order, "shipping": shipping}
Вариант 2
# asyncpg + httpx.AsyncClient (или aiohttp)
@app.get("/orders/{id}")
async def get_order(id: int, session: AsyncSession = Depends(get_session)):
order = await session.scalar(select(Order).where(Order.id == id))
async with httpx.AsyncClient() as client:
shipping = (await client.get(f"http://ship/{id}")).json()
return {"order": order, "shipping": shipping}
Чтобы решить вопрос и сохранить попытку — войди.