hyzyla / fastapi-async-sqlalchemy-orm

FastAPI + async SQLAlchemy ORM + async_scoped_session
MIT License
4 stars 0 forks source link

Can you get sessions from non web requests? #1

Open himat opened 1 year ago

himat commented 1 year ago

Great repo, thank you!

Question on this line though if I were to use fastapi async sqlalchemy with celery as well

From https://github.com/hyzyla/fastapi-async-sqlalchemy-orm/blob/main/app/db.py

# Function `get_session_context` controls when to create a new session.
# In our case, a new session context will be created for every request,
# so calling session methods inside the HTTP handlers will create one
# session per request.

Will what you have here only work when you do db.session.x from inside a HTTP route in fastapi, or will the code you have work as well for if I need to do db operations within a celery task (since there is no request inside a celery task)?

hyzyla commented 1 year ago

No, it won't work with celery task out of the box. You have to create your custom task class, like here https://stackoverflow.com/questions/6393879/celery-task-and-customize-decorator. And then create session scope for each task, the same way as we have in middleware