Section A.3. Data Mapper and Active Record

A.3. Data Mapper and Active Record

As discussed initially in Chapter 8, "RSS, Cookies, and Dynamic Views in WhatWhat Status," SQLObject follows the Active Record design pattern. In short, this pattern says that each table in your database is represented by a Python class. Instances of those objects directly represent rows in the database table.

The Data Mapper pattern adds an extra layer. There are classes that represent the tables in the database, but there are also objects that separately map from database tables to your classes. The Data Mapper pattern has some advantages over Active Record:

  1. Your classes are not tied to the database. They can freely be used in other contexts, such as tests, without worrying about database setup.

  2. Any "relation," in relational database management system (RDBMS) terms, can be mapped. This means that the results of arbitrary queries can be mapped to Python objects.

  3. Python objects can be composed of data from different tables.

The drawback to the Data Mapper pattern is that it requires more setup. Instead of setting up one class, you now have two to worry about. It turns out, though, that the Data Mapper pattern is a superset of Active Record. There is an extension included with SQLAlchemy called ActiveMapper. When your Python class subclasses ActiveMapper, ActiveMapper creates Table and Mapper objects behind the scenes, giving you the same ease-of-use that you get from an Active Record-based library such as SQLObject.

Choosing to use ActiveMapper at the beginning of the project does not mean you lose any of SQLAlchemy's power. You can still access a class's Table object by looking up the table class property:

    class Plate(ActiveMapper):         class mapping:             size = column(Integer)     print type(Plate.table)     <class 'sqlalchemy.schema.Table'>

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

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: