Session
- Python course
- Advanced
- Lesson 44/83
- 5 min
Learn session management with sessionmaker.
Session
sessionmaker is a factory class that produces sessions. Bound to an Engine, each Session() call returns a new session. All database operations go through a session.
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
session.add(obj)
session.commit()The session manages transactions; commit makes changes permanent, rollback undoes them. You close the session when done.
commit and rollback
Objects added to the session are not written to the database until commit() is called. On error, rollback() undoes the transaction.
session.add(User(name="Ayşe"))
session.commit() # make permanent
# or on error:
session.rollback() # undoWhen done, close the session with session.close(). This returns the connection to the pool. You can open and close many sessions on the same engine.
Practice Create Session and print its type
Start with from sqlalchemy import create_engine and from sqlalchemy.orm import sessionmaker. Define engine = create_engine("sqlite:///:memory:"). Create a session factory with Session = sessionmaker(bind=engine). Open a session with session = Session(). Print the class name with print(type(session).__name__).
Starter code
# bring in create_engine and sessionmaker from sqlalchemy
# define an engine (sqlite memory)
# create a session factory bound to the engine
# open a session from the factory
# print the session's class nameSample solution
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine("sqlite:///:memory:")
Session = sessionmaker(bind=engine)
session = Session()
print(type(session).__name__)Expected output
Session
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the sessionmaker call
from sqlalchemy.orm import sessionmaker
Session = ____(bind=engine)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
Explanation: sessionmaker(bind=engine) creates a session factory.
2 What does session.commit do?
- Closes the session
- Runs a query
- Makes changes permanent Correct answer
- Creates an Engine
Explanation: commit writes the session's changes to the database permanently.
3 Match the Session concepts
| Term | Meaning |
|---|---|
sessionmaker |
Is a session factory |
bind=engine |
Binds the engine |
session.add |
Adds an object |
session.commit |
Makes permanent |