CodexBloom - Programming Q&A Platform

implementing FastAPI and SQLAlchemy when using async sessions in Python 3.11

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

Could someone explain I'm a bit lost with I'm getting frustrated with I can't seem to get I'm trying to figure out I've looked through the documentation and I'm still confused about I'm currently building a RESTful API using FastAPI and SQLAlchemy, but I'm running into issues when trying to manage my database sessions asynchronously..... I have defined my database models and a SQLAlchemy async session, but when I attempt to create a new record, I get an behavior: `AttributeError: 'AsyncSession' object has no attribute 'commit'`. Here's the relevant code snippet: ```python from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname" gine = create_async_engine(DATABASE_URL, echo=True) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async def create_user(name: str): async with async_session() as session: new_user = User(name=name) session.add(new_user) await session.commit() # This line is causing the behavior ``` I've already checked that I'm using the correct `AsyncSession` and the right imports from `sqlalchemy.ext.asyncio`. To troubleshoot, I tried running a simplified version of the code without the session context manager, but that didn't help. What’s the correct way to handle commits with async sessions in SQLAlchemy? Are there any specific configurations or methods that I might be missing here? Any insights would be greatly appreciated! I'm working with Python in a Docker container on CentOS. I appreciate any insights! For context: I'm using Python on CentOS. Any advice would be much appreciated. I'd really appreciate any guidance on this.