You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
engine singleton Built in SQLmodel or make my own ? #123
I used the GitHub search to find a similar issue and didn't find it.
I searched the SQLModel documentation, with the integrated search.
I already searched in Google "How to X in SQLModel" and didn't find any information.
I already read and followed all the tutorial in the docs and didn't find an answer.
I already checked if it is not related to SQLModel but to Pydantic.
I already checked if it is not related to SQLModel but to SQLAlchemy.
Commit to Help
I commit to help with one of those options 👆
Example Code
Architecturequestion, nocodeneeded.
Description
I need the "engine" instance in my services and routers to create "session" to access the database?
define this somewhere
engine = create_engine(sqlite_url, echo=False)
use this everywhere
session = Session(engine)
All samples are single file examples so no imports of engine.
It is unclear to me if SQLModel has a solution or should I create my own singleton to hold the engine instance.
My Flask background had me put the engine from SqlAlchemy to the app instance, is this prefred in FastApi (But not sure if I can import the app instance from main.py).
..then you only need to just create the engine in the same module as where you define the get_session() function. e.g. if you have a "db.py", you can just have something like:
Then when you define your router endpoints, just import and use get_session with Depends as described in the documentation I linked to above.
That's roughly a simplified version of how I do it, anyway...
So, not that different from the single-file examples in the tutorial, just moving the create_engine and get_session code to a separate module, and importing that.
Activity
LucidDan commentedon Oct 6, 2021
If you use this style of dependency for getting the database session - https://sqlmodel.tiangolo.com/tutorial/fastapi/session-with-dependency/#create-a-fastapi-dependency
..then you only need to just create the engine in the same module as where you define the get_session() function. e.g. if you have a "db.py", you can just have something like:
Then when you define your router endpoints, just import and use get_session with Depends as described in the documentation I linked to above.
That's roughly a simplified version of how I do it, anyway...
So, not that different from the single-file examples in the tutorial, just moving the create_engine and get_session code to a separate module, and importing that.