ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 2727

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

1 from pyramid.view import view_config

2

3 from .models import (

4DBSession,

5MyModel,

6)

7

8 @view_config(route_name=’home’, renderer=’templates/mytemplate.pt’) 9 def my_view(request):

10one = DBSession.query(MyModel).filter(MyModel.name==’one’).first()

11return {’one’:one, ’project’:’tutorial’}

The important part here is that the @view_config decorator associates the function it decorates (my_view) with a view configuration, consisting of:

a route_name (home)

a renderer, which is a template from the templates subdirectory of the package.

When the pattern associated with the home view is matched during a request, my_view() will be executed. my_view() returns a dictionary; the renderer will use the templates/mytemplate.pt template to create a response based on the values in the dictionary.

Note that my_view() accepts a single argument named request. This is the standard call signature for a Pyramid view callable.

Remember in our __init__.py when we executed the pyramid.config.Configurator.scan() method, i.e. config.scan()? The purpose of calling the scan method was to find and process this @view_config decorator in order to create a view configuration within our application. Without being processed by scan, the decorator effectively does nothing. @view_config is inert without being detected via a scan.

37.4.3 Content Models with models.py

In a SQLAlchemy-based application, a model object is an object composed by querying the SQL database. The models.py file is where the alchemy scaffold put the classes that implement our models.

Open tutorial/tutorial/models.py. It should already contain the following:

452

37.4. BASIC LAYOUT

1 from sqlalchemy import (

2Column,

3Integer,

4Text,

5)

6

7 from sqlalchemy.ext.declarative import declarative_base

8

9 from sqlalchemy.orm import (

10scoped_session,

11sessionmaker,

12)

13

14 from zope.sqlalchemy import ZopeTransactionExtension

15

16DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

17Base = declarative_base()

18

19class MyModel(Base):

20__tablename__ = ’models’

21id = Column(Integer, primary_key=True)

22name = Column(Text, unique=True)

23value = Column(Integer)

24

25def __init__(self, name, value):

26self.name = name

27self.value = value

Let’s examine this in detail. First, we need some imports to support later code:

1 from sqlalchemy import (

2Column,

3Integer,

4Text,

5)

6

7 from sqlalchemy.ext.declarative import declarative_base

8

9 from sqlalchemy.orm import (

10scoped_session,

11sessionmaker,

12)

13

14 from zope.sqlalchemy import ZopeTransactionExtension

453


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/.

454


37.5. DEFINING THE DOMAIN MODEL

37.5.1 Making Edits to models.py

latex-note.png

There is nothing automagically special about the filename models.py. A project may have many models throughout its codebase in arbitrarily-named files. Files implementing models often have model in their filenames (or they may live in a Python subpackage of your application package named models) , but this is only by convention.

Open tutorial/tutorial/models.py file and edit it to look like the following:

1 from sqlalchemy import (

2Column,

3Integer,

4Text,

5)

6

7 from sqlalchemy.ext.declarative import declarative_base

8

9 from sqlalchemy.orm import (

10scoped_session,

11sessionmaker,

12)

13

14 from zope.sqlalchemy import ZopeTransactionExtension

15

16DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

17Base = declarative_base()

18

19class Page(Base):

20""" The SQLAlchemy declarative model class for a Page object. """

21__tablename__ = ’pages’

22id = Column(Integer, primary_key=True)

23name = Column(Text, unique=True)

24data = Column(Text)

25

26def __init__(self, name, data):

27self.name = name

28self.data = data

455


37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

(The highlighted lines are the ones that need to be changed.)

The first thing we’ve done is to do is remove the stock MyModel class from the generated models.py file. The MyModel class is only a sample and we’re not going to use it.

Then, we added a Page class. Because this is a SQLAlchemy application, this class inherits from an instance of sqlalchemy.ext.declarative.declarative_base.

1

class Page(Base):

2

""" The SQLAlchemy declarative model class for a Page object. """

3__tablename__ = ’pages’

4 id = Column(Integer, primary_key=True) 5 name = Column(Text, unique=True)

6data = Column(Text)

7

8 def __init__(self, name, data): 9 self.name = name

10 self.data = data

As you can see, our Page class has a class level attribute __tablename__ which equals the string ’pages’. This means that SQLAlchemy will store our wiki data in a SQL table named pages. Our Page class will also have class-level attributes named id, name and data (all instances of sqlalchemy.Column). These will map to columns in the pages table. The id attribute will be the primary key in the table. The name attribute will be a text attribute, each value of which needs to be unique within the column. The data attribute is a text attribute that will hold the body of each page.

37.5.2 Changing scripts/initializedb.py

We haven’t looked at the details of this file yet, but within the scripts directory of your tutorial package is a file named initializedb.py. Code in this file is executed whenever we run the initialize_tutorial_db command (as we did in the installation step of this tutorial).

Since we’ve changed our model, we need to make changes to our initializedb.py script. In particular, we’ll replace our import of MyModel with one of Page and we’ll change the very end of the script to create a Page rather than a MyModel and add it to our DBSession.

Open tutorial/tutorial/scripts/initializedb.py and edit it to look like the following:

456

37.5. DEFINING THE DOMAIN MODEL

1

import os

2

import sys

3

import transaction

4

 

5

from sqlalchemy import engine_from_config

6

 

7

from pyramid.paster import (

8get_appsettings,

9setup_logging,

10

)

11

 

12from ..models import (

13DBSession,

14Page,

15Base,

16)

17

18def usage(argv):

19cmd = os.path.basename(argv[0])

20print(’usage: %s <config_uri>\n

21’(example: "%s development.ini")’ % (cmd, cmd))

22sys.exit(1)

23

24def main(argv=sys.argv):

25if len(argv) != 2:

26usage(argv)

27config_uri = argv[1]

28setup_logging(config_uri)

29settings = get_appsettings(config_uri)

30engine = engine_from_config(settings, ’sqlalchemy.’)

31DBSession.configure(bind=engine)

32Base.metadata.create_all(engine)

33with transaction.manager:

34model = Page(’FrontPage’, ’This is the front page’)

35DBSession.add(model)

(Only the highlighted lines need to be changed.)

37.5.3 Reinitializing the Database

Because our model has changed, in order to reinitialize the database, we need to rerun the initialize_tutorial_db command to pick up the changes you’ve made to both the models.py

457


37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

file and to the initializedb.py file. From the root of the tutorial project, directory execute the following commands.

On UNIX:

$ ../bin/initialize_tutorial_db development.ini

On Windows:

c:\pyramidtut\tutorial> ..\Scripts\initialize_tutorial_db development.ini

Success will look something like this:

2011-11-27

01:22:45,277 INFO

[sqlalchemy.engine.base.Engine][MainThread]

 

 

 

PRAGMA table_info("pages")

 

2011-11-27

01:22:45,277 INFO

[sqlalchemy.engine.base.Engine][MainThread] ()

2011-11-27

01:22:45,277 INFO

[sqlalchemy.engine.base.Engine][MainThread]

CREATE TABLE pages (

 

 

id INTEGER NOT NULL,

 

 

name TEXT,

 

 

data TEXT,

 

 

PRIMARY KEY (id),

 

 

UNIQUE (name)

 

 

)

 

 

 

2011-11-27 01:22:45,278 INFO

[sqlalchemy.engine.base.Engine][MainThread] ()

2011-11-27 01:22:45,397 INFO

[sqlalchemy.engine.base.Engine][MainThread]

 

 

COMMIT

2011-11-27 01:22:45,400 INFO

[sqlalchemy.engine.base.Engine][MainThread]

 

 

BEGIN (implicit)

2011-11-27 01:22:45,401 INFO

[sqlalchemy.engine.base.Engine][MainThread]

 

 

INSERT INTO pages (name, data) VALUES (?, ?)

2011-11-27 01:22:45,401 INFO

[sqlalchemy.engine.base.Engine][MainThread]

 

 

(’FrontPage’, ’This is the front page’)

2011-11-27 01:22:45,402 INFO

[sqlalchemy.engine.base.Engine][MainThread]

 

 

COMMIT

 

 

 

 

37.5.4 Viewing the Application in a Browser

We can’t. At this point, our system is in a “non-runnable” state; we’ll need to change view-related files in the next chapter to be able to start the application successfully. If you try to start the application (See

458