37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL
Next we set up a SQLAlchemy “DBSession” object:
1 DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
scoped_session and sessionmaker are standard SQLAlchemy helpers. scoped_session allows us to access our database connection globally. sessionmaker creates a database session object. We pass to sessionmaker the extension=ZopeTransactionExtension() extension option in order to allow the system to automatically manage datbase transactions. With ZopeTransactionExtension activated, our application will automatically issue a transaction commit after every request unless an exception is raised, in which case the transaction will be aborted.
We also need to create a declarative Base object to use as a base class for our model:
Base = declarative_base()
Our model classes will inherit from this Base class so they can be associated with our particular database connection.
To give a simple example of a model class, we define one named MyModel:
1 class MyModel(Base):
2__tablename__ = ’models’
3 id = Column(Integer, primary_key=True) 4 name = Column(Text, unique=True)
5value = Column(Integer)
6
7 def __init__(self, name, value):
8self.name = name
9self.value = value
Our example model has an __init__ that takes a two arguments (name, and value). It stores these values as self.name and self.value within the __init__ function itself. The MyModel class also has a __tablename__ attribute. This informs SQLAlchemy which table to use to store the data representing instances of this class.
That’s about all there is to it to models, views, and initialization code in our stock application.
37.5 Defining the Domain Model
The first change we’ll make to our stock pcreate-generated application will be to define a domain model constructor representing a wiki page. We’ll do this inside our models.py file.
The source code for this tutorial stage can be browsed at http://github.com/Pylons/pyramid/tree/1.3- branch/docs/tutorials/wiki2/src/models/.