Skip to content

Configuring the Database Connection

Before using SQLAlchemy to store or retrieve data, configure its database connection. Since we use SQLite, choose a database file path and provide it to SQLAlchemy.

Creating the Connection File

Create connection.py alongside main.py to keep connection settings in one place.

connection.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "sqlite:///./app.db"  # ①

engine = create_engine(DATABASE_URL, echo=True)  # ②

SessionFactory = sessionmaker(  # ③
    bind=engine,  # ④
    autoflush=False,  # ⑤
    autocommit=False,
    expire_on_commit=False,
)
  • ① DATABASE_URL specifies the SQLite connection URL. sqlite:/// selects SQLite, and ./app.db is relative to the folder where you start the server.
  • ② Pass the URL to create_engine() to create an engine. It knows the database location and manages connections used for queries and writes. With echo=True, SQL statements appear in the terminal logs.
  • ③ sessionmaker() creates SessionFactory, an object that produces sessions. A session queries ORM data and applies object changes to the database. Each call to SessionFactory() creates a new session.
  • ④ bind receives the SQLite engine from ②, so sessions from this factory use that engine to connect.
  • ⑤ autoflush, autocommit, and expire_on_commit control automatic session behavior. We set them to False here to control the session's data processing explicitly.

Server code requests operations through a session, which uses an engine connection to execute SQL

Defining the Post Model

Create model.py alongside connection.py. First, define Base.

model.py
from sqlalchemy.orm import DeclarativeBase


class Base(DeclarativeBase):
    pass

Base inherits from DeclarativeBase and serves as the common parent for this project's ORM models. Subclasses map to database tables. SQLAlchemy collects their table names and column definitions in Base.metadata.

Now define Post, representing the posts table we will create. The model and sessions let us retrieve and save posts without writing SQL directly.

model.py
from sqlalchemy import String, Text
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


class Post(Base):  # ①
    __tablename__ = "posts"

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)  # ②
    title: Mapped[str] = mapped_column(String(100))  # ③
    content: Mapped[str] = mapped_column(Text)  # ④
  • ① Post represents one post as a Python object. __tablename__ = "posts" maps its instances to rows in that table.
  • ② id is the primary key (PK) identifying each post. mapped_column() defines a column; primary_key=True marks it as the primary key. With autoincrement=True, the database assigns IDs when saving new posts, starting at 1 for an empty table.

    Type hints describe the values exposed by model attributes. Mapped[int] indicates a mapped column whose value on a post instance is an integer.

  • ③ title stores the post title. String(100) declares a length of 100 characters.

  • ④ content uses Text for longer strings such as a post body.

Creating the Tables

We can now create the table without writing SQL. With the environment active, navigate to the folder containing model.py and run python -i model.py.

$ python -i model.py

The -i flag keeps Python in interactive mode after executing the file, with Base and Post available. Enter these lines at the >>> prompt:

>>> from connection import engine
>>> Base.metadata.create_all(bind=engine)

Base.metadata.create_all() creates registered tables that do not yet exist. Since the engine uses echo=True, you will see CREATE TABLE posts in the terminal when it is created.

On the first run, SQLite creates app.db and its posts table. Check the VS Code Explorer for app.db alongside model.py.

In the same interactive session, inspect the actual database table names:

>>> from sqlalchemy import inspect
>>> inspect(engine).get_table_names()
['posts']

If the result includes posts, the table exists.

Press Ctrl+D when finished to exit interactive mode.

Check Your Understanding

Decide whether each statement is true or false.

  1. A SQLAlchemy engine manages database connections.
  2. Calling a session factory repeatedly always returns the same session object.
  3. A primary key uniquely identifies each row in a table.
  4. Defining an ORM model class automatically creates its table in the database.
  5. SQLAlchemy can inspect which tables exist in a database.
Answers and Explanations
  1. True — Sessions obtain connections from the engine for database operations.
  2. False — Each factory call creates a new session.
  3. True — Primary key values distinguish rows.
  4. False — A model defines the structure; a separate operation creates the table.
  5. True — SQLAlchemy can query the connected database's table list.