CodexBloom - Programming Q&A Platform

scenarios when using Django async views with SQLAlchemy ORM in FastAPI

πŸ‘€ Views: 1 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
fastapi sqlalchemy asyncio Python

I keep running into I'm relatively new to this, so bear with me..... I'm trying to use async views in my FastAPI application, but I'm running into issues when I attempt to use SQLAlchemy ORM for database interactions. Specifically, I have a FastAPI route that looks something like this: ```python from fastapi import FastAPI, Depends from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname" engine = create_async_engine(DATABASE_URL) AsyncSessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False) app = FastAPI() async def get_db() -> AsyncSession: async with AsyncSessionLocal() as session: yield session @app.get("/items/{item_id}") async def read_item(item_id: int, db: AsyncSession = Depends(get_db)): result = await db.execute(select(Item).where(Item.id == item_id)) return result.scalars().first() ``` However, when I try to access this endpoint, I'm getting the following behavior: ``` RuntimeError: Task <Task pending name='Task-1' coro=<FastAPI.__call__() running at ...> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at ...>()]>] got Future <Future pending> attached to a different loop ``` I've ensured that my environment is using the same version of `asyncpg` and `sqlalchemy` (1.4.27) but I'm not sure if it’s due to the event loop handling in FastAPI. I’ve tried using `asyncio.run()` in various places, but it hasn’t resolved the scenario. Could someone guide to understand how to properly use async with FastAPI and SQLAlchemy without running into this event loop question? Any insights or configurations I might be missing would be greatly appreciated. This is part of a larger application I'm building. My team is using Python for this CLI tool. Am I missing something obvious? I'm using Python 3.10 in this project.