Here’s what’s happening—step by step—when you run
engine = create_engine(SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False})
-
create_engine(...)
• Comes from SQLAlchemy (from sqlalchemy import create_engine).
• Creates an Engine object, the central object that SQLAlchemy uses to talk to your database.
• Think of the Engine as a factory for DB-API connections plus a “dialect” (the logic that knows how to speak PostgreSQL, MySQL, SQLite, etc.).
-
SQLALCHEMY_DATABASE_URL
• A string (URL style) that tells SQLAlchemy which database to connect to and how.
• Examples:
- SQLite file:
sqlite:///./app.db
- PostgreSQL:
postgresql+psycopg2://user:password@localhost/dbname
- MySQL:
mysql+pymysql://user:pw@localhost:3306/db
-
connect_args={"check_same_thread": False}
• connect_args lets you pass driver-specific arguments down to the underlying DB-API (the low-level driver).
• The snippet you’re looking at is almost always used with SQLite (sqlite:///…).
• SQLite’s Python driver (sqlite3) has a safety flag check_same_thread that defaults to True.
– When True, a connection can be used only in the thread where it was created.
– When False, you can share the same connection across multiple threads (e.g., in a web server like Uvicorn or Gunicorn that spawns multiple worker threads).
• So we set it to False to avoid “SQLite objects created in a thread can only be used in that same thread” errors.
Why it’s common in FastAPI tutorials
FastAPI (and Starlette under the hood) is async-friendly and often handles requests in multiple threads. If you’re using SQLite during development, you need check_same_thread=False so each web-request handler can talk to the same database connection without crashing.
Caveat
SQLite + multi-threading is okay for local dev and small projects, but for production you’ll usually switch to PostgreSQL, MySQL, etc., where the thread restriction doesn’t exist.
Tiny demo
from sqlalchemy import create_engine, text
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
with engine.connect() as conn:
conn.execute(text("CREATE TABLE IF NOT EXISTS hello (id INTEGER)"))
conn.execute(text("INSERT INTO hello (id) VALUES (1)"))
result = conn.execute(text("SELECT * FROM hello"))
print(result.all()) # → [(1,)]
That’s it! An Engine ready to hand out connections to your SQLite (or other) database, with the thread-safety knob adjusted as needed.