Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
pyramid.pdf
Скачиваний:
10
Добавлен:
24.03.2015
Размер:
3.82 Mб
Скачать

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

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]