mongkok / fastapi-debug-toolbar

A debug toolbar for FastAPI.
https://fastapi-debug-toolbar.domake.io
BSD 3-Clause "New" or "Revised" License
140 stars 14 forks source link

sqlalchemy use problem #12

Closed 65tech closed 1 year ago

65tech commented 2 years ago

show "No SQL queries were recorded during this request."

armando-herastang commented 2 years ago

Also having this issue! Haven't look into it further. But no queries are shown

Satchitananda commented 2 years ago

Same here

florimondmanca commented 2 years ago

In my case, I found that this is because fastapi-debug-toolbar expects a db: Session = Depends(...) annotation on the route, as hinted in the README:

Please make sure to use the "Dependency Injection" system as described in the FastAPI docs

But a/ I don't use this style, as I use a different DI system than FastAPI's (I use punq), and b/ I use SQLAlchemy async support, so the session would be an AsyncSession anyway -- yet the code explicitly checks for Session subclass on the dependency.

To get things working, I had to subclass the default panel and override how the engine is registered for SQLAlchemy events, passing the project's SQLAlchemy engine myself:

from debug_toolbar.panels.sqlalchemy import SQLAlchemyPanel as Base
from fastapi import Request, Response

from server.config.di import resolve
from server.infrastructure.database import Database

class SQLAlchemyPanel(Base):
    async def process_request(self, request: Request) -> Response:
        db = resolve(Database)
        engine = db.engine.sync_engine

        self.register(engine)
        try:
            return await super().process_request(request)
        finally:
            self.unregister(engine)

(My actual implementation also includes the JSON dump fix from #15.)

Then use this by passing its Python module path to panels=....

Then I am able to see queries in the SQLAlchemy section of debug toolbar.

Hope this helps!

mongkok commented 1 year ago

Hey @65tech , A new release was created related with this, see v0.3.0.

If you are using FastAPI dependencies add SQLAlchemyPanel to the panel list, the panel supports now fastapi>=0.74.0. If you don't use dependencies then create a new class that inherits from SQLAlchemyPanel, override the add_engines method and add the class path to your panel list, see #21:

from debug_toolbar.panels.sqlalchemy import SQLAlchemyPanel as BasePanel
from sqlalchemy import create_engine

engine = create_engine("sqlite://...", connect_args={"check_same_thread": False})

class SQLAlchemyPanel(BasePanel):
    async def add_engines(self, request: Request):
        self.engines.add(engine)

Thanks @florimondmanca for your help on this.