sqlalchemy Creating a Session


A session is usually obtained using sessionmaker, which creates a Session class unique to your application. Most commonly, the Session class is bound to an engine, allowing instances to use the engine implicitly.

from sqlalchemy.orm import sessionmaker

# Initial configuration arguments
Session = sessionmaker(bind=engine)

The engine and Session should only be created once.

A session is an instance of the class we created:

# This session is bound to provided engine
session = Session()

Session.configure() can be used to configure the class later, e.g. application startup rather than import time.

Session = sessionmaker()

# later

Arguments passed to Session directly override the arguments passed to sessionmaker.

session_bound_to_engine2 = Session(bind=engine2)