Create the Database Engine
Create database.py with the SQLite engine and table creation function
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
What the engine does
The engine is the object that manages the connection to your database. It holds the database location and knows how to open and close connections. Everything that reads from or writes to SQLite goes through the engine.
You create one engine for the entire application and reuse it across all requests.
The connection URL
SQLModel uses a connection URL to identify the database:
engine = create_engine("sqlite:///expenses.db")sqlite://— use the SQLite database engine/expenses.db— store the database in a file calledexpenses.dbin your project directory
Three slashes (sqlite:///) means a relative path. If you wanted an absolute path, you would use four slashes.
Why check_same_thread=False
SQLite's default behavior rejects connections that are used from a different thread than the one that created them. FastAPI can route a single HTTP request through multiple threads internally, which triggers this check and raises an error.
Setting check_same_thread=False disables that check. Each request still gets its own session — you will set that up in the next chapter — so threads do not actually share connections. The flag just tells SQLite not to enforce the restriction.
Creating the table
create_db_and_tables() calls SQLModel.metadata.create_all(engine). This inspects all your SQLModel table models, checks whether their tables exist in the database, and creates any that are missing.
It is safe to call every time your app starts. If the expense table already exists, the call does nothing.
Instructions
Create database.py with the engine and table creation function.
- Import
SQLModelandcreate_enginefromsqlmodel. - Create a variable called
engineby callingcreate_enginewith two arguments:"sqlite:///expenses.db"— the database file locationconnect_args={"check_same_thread": False}— allows SQLite to work across FastAPI's threads
- Define a function called
create_db_and_tables. Inside it, callSQLModel.metadata.create_all(engine).
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding