I'm using FastAPI, aiosqlite and SqlAlchemy. The application works fine, but I get this exception when I add a middleware. The request returns 200 code, but then the exception is raised. Do you have any suggestion?
Exception:
Exception closing connection <AdaptedConnection <Connection(Thread-1, started daemon 140230447978048)>>
Main file:
from database import engine, Base, async_session
from dependencies import get_session, validate_authorization, validate_admin
from typing import List, Optional
app = FastAPI(title="Title", docs_url="/docs", redoc_url="/redocs", openapi_url=None)
@app.middleware("http")
async def verify_authorization(request: Request, call_next):
token = request.headers.get('Authorization')
#print(token, end="\n\n")
#if not token or not validate_authorization(token):
# raise HTTPException(status_code=401, detail="Not valid authorization token.")
response = await call_next(request)
return response
database.py:
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
SQLALCHEMY_DATABASE_URL = "sqlite+aiosqlite:///./DB.db"
#SQLALCHEMY_DATABASE_URL = "postgresql+asyncpg://user:password@localhost/db"
engine = create_async_engine(SQLALCHEMY_DATABASE_URL, future=False, echo=False, connect_args={"check_same_thread": False})
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
Base = declarative_base()
dependencies.py
from fastapi import HTTPException
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import update, delete, select, insert
from typing import AsyncGenerator
from database import async_session
async def get_session() -> AsyncGenerator:
async with async_session() as session:
try:
yield session
await session.commit()
except SQLAlchemyError as sql_ex:
await session.rollback()
raise sql_ex
except HTTPException as http_ex:
await session.rollback()
raise http_ex
finally:
await session.close()