Skip to Main Content
Essential SQLAlchemy
book

Essential SQLAlchemy

by Rick Copeland
June 2008
Intermediate to advanced content levelIntermediate to advanced
230 pages
6h 29m
English
O'Reilly Media, Inc.
Content preview from Essential SQLAlchemy

Chapter 7. Querying and Updating at the ORM Level

This chapter introduces the SQLAlchemy Session object. You will learn how to use the Session to perform queries and updates of mapped classes, as well as how to customize the Session class and create a “contextual” session that simplifies session management.

The SQLAlchemy ORM Session Object

SQLAlchemy manages all querying and updating of objects in the ORM with Session objects. The Session is responsible for implementing the unit of work pattern of synchronization between in-memory objects and database tables. Sessions also provide a rich interface for querying the database based on object attributes rather than the underlying SQL database structure.

Creating a Session

The first step in creating a session is to obtain a Session object from SQLAlchemy. One way to do this is to directly instantiate the sqlalchemy.orm.session.Session class. However, this constructor for the SQLAlchemy-provided Session has a number of keyword arguments, making instantiating Sessions in this manner verbose and tedious. In order to alleviate this burden, SQLAlchemy provides the sessionmaker() function, which returns a subclass of orm.session.Session with default arguments set for its constructor.

Once you have this customized Session class, you can instantiate it as many times as necessary in your application without needing to retype the keyword arguments (which in many applications will not change between Session instantiations). If you wish to override ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning PostgreSQL

Learning PostgreSQL

Salahaldin Juba, Achim Vannahme, Andrey Volkov
Practical PostgreSQL

Practical PostgreSQL

Joshua D. Drake, John C. Worsley
PostgreSQL

PostgreSQL

Korry Douglas, Susan Douglas
Learning PostgreSQL 11 - Third Edition

Learning PostgreSQL 11 - Third Edition

Christopher Travers, Andrey Volkov

Publisher Resources

ISBN: 9780596516147Supplemental ContentErrata Page