Table of Contents
Since we’re in a database-driven world, in practice the model will be based on a relational database. SQLAlchemy/SQLObject makes working with databases easy.
Elixir is a a declarative layer on top of SQLAlchemy. It remains the simplicity like SQLObject and the flexibility of SQLAlchemy.
For a real web application the very first thing you should customize is the location of the database your TurboGears app will use.
- setup a dburi
- setup an engine
- connect engine with an session
- manipulate the database
- flush the change back to the database.
Open dev.cfg and find the appropriate commented line for the SQL implementation you will be using. For this tutorial I will use SQLite because it uses a local file instead of a server connection:
sqlalchemy.dburi = "sqlite:///home/username/tutorial/tutorial.sqlite"
Note
If you choose SQLite, the URI must be an absolute path. And of course, you’ll need SQLite installed.
Note
The alternative is:
sqlalchemy.dburi = "sqlite://%(current_dir_uri)s/devdata.sqlite"
%(current_dir_uri)s is a TurboGears config shortcut for current path.
To define your database tables, open the existing file tutorial/model.py. TurboGears uses Elixir over SQLalchemy for database abstraction. In Elixir, classes represent tables and class attributes represent columns. Since I’m making a to-do list application, I added the following classes in tutorial/model.py:
from sqlalchemy import *
from turbogears.database import metadata, session
from elixir import *
class User(Entity):
has_field('email', String)
has_many('lists', of_kind='List')
class List(Entity):
has_field('title', Unicode, nullable=False)
belongs_to('user', of_kind='User')
has_many('items', of_kind='Item')
class Item(Entity):
has_field('value', Unicode, nullable=False)
belongs_to('list', of_kind='List')
In this model, users are uniquely identified by their e-mail address and can have multiple lists. Lists have a title, an owner, and multiple items. Items have a value and their containing list.
See the Elixir documentation for help with defining and using your tables:
For a comparison between SQLAlchemy and Elixir, see also: