mfreeborn / fastapi-sqlalchemy

Adds simple SQLAlchemy support to FastAPI
MIT License
594 stars 34 forks source link

BaseHTTPMiddleware based Middleware Breaks Background Tasks #25

Open cancan101 opened 3 years ago

cancan101 commented 3 years ago

The current middleware subclasses BaseHTTPMiddleware which per https://github.com/encode/starlette/issues/919 and https://github.com/tiangolo/fastapi/issues/2086 will cause all background tasks to run before the response is sent. Better would be to not subclass BaseHTTPMiddleware.

Instead the class would look like:

class DBSessionMiddleware:
    def __init__(self, app....)
....

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        with db():
            await self.app(scope, receive, send)