engine singleton Built in SQLmodel or make my own ? #1510
-
First Check
Commit to Help
Example CodeArchitecture question, no code needed. DescriptionI need the "engine" instance in my services and routers to create "session" to access the database? define this somewhere
use this everywheresession = 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). Operating SystemWindows Operating System DetailsNo response SQLModel Version0.0.4 Python Version3.9.7 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
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: # ... imports, etc ...
engine = create_engine(sqlite_url, echo=False)
def get_session():
with Session(engine) as session:
yield session 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. |
Beta Was this translation helpful? Give feedback.
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...