Section A.5. How Objects Are Cached in SQLAlchemy


A.5. How Objects Are Cached in SQLAlchemy

SQLObject includes some options (lazyUpdate and cacheValues) to control how SQLObject caches values. Most people don't use these options, and SQLAlchemy doesn't offer the equivalent options because its caching is simpler.

SQLAlchemy is built around a "unit-of-work" pattern, as described by Martin Fowler in Patterns of Enterprise Application Architecture. This means that you typically work with various objects while accomplishing a specific task. In SQLAlchemy, you have session objects that hang on to all the objects you're working with in a unit of work. TurboGears maintains one for you as turbogears.database.session. When an object needs to be retrieved from the database, its primary key is first looked up in the session. If it's already present in the session, the existing object is returned directly:

    >>> page1 = Page.get(1)     >>> page2 = Page.get(1)     >>> page1 is page2     True


SQLAlchemy does not issue any database update commands until the session is told to "flush." Objects loaded from the database will stick around until clear is called on the session. TurboGears automatically flushes the session, commits the database transaction, and clears the session at the end of the request.

If you are working with many objects or need to explicitly refresh an object from the database, you can call methods on the session to flush and clear objects as needed.

When using SQLObject with TurboGears, you are already following a pattern similar to SQLAlchemy's unit of work because of how TurboGears handles transactions.




Rapid Web Applications with TurboGears(c) Using Python to Create Ajax-Powered Sites
Rapid Web Applications with TurboGears: Using Python to Create Ajax-Powered Sites
ISBN: 0132433885
EAN: 2147483647
Year: 2006
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net