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

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

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

Добавлен: 02.01.2026

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

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

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

37.3. INSTALLATION

37.3.6 Initializing the Database

We need to use the initialize_tutorial_db console script to initialize our database.

Type the following command, make sure you are still in the tutorial directory (the directory with a development.ini in it):

On UNIX:

$ ../bin/initialize_tutorial_db development.ini

On Windows:

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

The output to your console should be something like this:

2011-11-26

14:42:25,012 INFO

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

 

 

 

PRAGMA table_info("models")

 

2011-11-26

14:42:25,013 INFO

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

2011-11-26

14:42:25,013 INFO

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

CREATE TABLE models (

 

 

id INTEGER NOT NULL,

 

 

name VARCHAR(255),

 

 

value INTEGER,

 

 

PRIMARY KEY (id),

 

 

UNIQUE (name)

 

 

)

 

 

 

2011-11-26 14:42:25,013 INFO

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

2011-11-26 14:42:25,135 INFO

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

 

 

COMMIT

2011-11-26 14:42:25,137 INFO

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

 

 

BEGIN (implicit)

2011-11-26 14:42:25,138 INFO

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

 

 

INSERT INTO models (name, value) VALUES (?, ?)

2011-11-26 14:42:25,139 INFO

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

 

 

(u’one’, 1)

2011-11-26 14:42:25,140 INFO

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

 

 

COMMIT

 

 

 

 

Success! You should now have a tutorial.db file in your current working directory. This will be a SQLite database with a single table defined in it (models).

447


37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

37.3.7 Starting the Application

Start the application.

On UNIX:

$ ../bin/pserve development.ini --reload

On Windows:

c:\pyramidtut\tutorial> ..\Scripts\pserve development.ini --reload

If successful, you will see something like this on your console:

Starting subprocess with file monitor

Starting server in PID 8966.

Starting HTTP server on http://0.0.0.0:6543

This means the server is ready to accept requests.

At this point, when you visit http://localhost:6543/ in your web browser, you will see the generated application’s default page.

One thing you’ll notice is the “debug toolbar” icon on right hand side of the page. You can read more about the purpose of the icon at The Debug Toolbar. It allows you to get information about your application while you develop.

37.3.8 Decisions the alchemy Scaffold Has Made For You

Creating a project using the alchemy scaffold makes the following assumptions:

you are willing to use SQLAlchemy as a database access tool

you are willing to use url dispatch to map URLs to code.

latex-note.png

Pyramid supports any persistent storage mechanism (e.g. object database or filesystem files, etc). It also supports an additional mechanism to map URLs to code (traversal). However, for the purposes of this tutorial, we’ll only be using url dispatch and SQLAlchemy.

448


37.4. BASIC LAYOUT

37.4 Basic Layout

The starter files generated by the alchemy scaffold are very basic, but they provide a good orientation for the high-level patterns common to most url dispatch -based Pyramid projects.

The source code for this tutorial stage can be browsed at http://github.com/Pylons/pyramid/tree/1.3- branch/docs/tutorials/wiki2/src/basiclayout/.

37.4.1 Application Configuration with __init__.py

A directory on disk can be turned into a Python package by containing an __init__.py file. Even if empty, this marks a directory as a Python package. We use __init__.py both as a marker indicating the directory it’s contained within is a package, and to contain configuration code.

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

1

from pyramid.config import Configurator

2

from sqlalchemy import engine_from_config

3

 

4

from .models import DBSession

5

 

6

def main(global_config, **settings):

7""" This function returns a Pyramid WSGI application.

8"""

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

10DBSession.configure(bind=engine)

11config = Configurator(settings=settings)

12config.add_static_view(’static’, ’static’, cache_max_age=3600)

13config.add_route(’home’, ’/’)

14config.scan()

15return config.make_wsgi_app()

Let’s go over this piece-by-piece. First, we need some imports to support later code:

1

2

3

4

from pyramid.config import Configurator from sqlalchemy import engine_from_config

from .models import DBSession

__init__.py defines a function named main. Here is the entirety of the main function we’ve defined in our __init__.py:

449


37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

1 def main(global_config, **settings):

2""" This function returns a Pyramid WSGI application.

3"""

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

5DBSession.configure(bind=engine)

6config = Configurator(settings=settings)

7 config.add_static_view(’static’, ’static’, cache_max_age=3600)

8config.add_route(’home’, ’/’)

9config.scan()

10 return config.make_wsgi_app()

When you invoke the pserve development.ini command, the main function above is executed. It accepts some settings and returns a WSGI application. (See Startup for more about pserve.)

The main function first creates a SQLAlchemy database engine using engine_from_config from the sqlalchemy. prefixed settings in the development.ini file’s [app:main] section. This will be a URI (something like sqlite://):

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

main then initializes our SQL database using SQLAlchemy, passing it the engine:

DBSession.configure(bind=engine)

The next step of main is to construct a Configurator object:

config = Configurator(settings=settings)

settings is passed to the Configurator as a keyword argument with the dictionary values passed as the **settings argument. This will be a dictionary of settings parsed from the .ini file, which contains deployment-related values such as pyramid.reload_templates, db_string, etc.

main now calls pyramid.config.Configurator.add_static_view() with two arguments: static (the name), and static (the path):

config.add_static_view(’static’, ’static’, cache_max_age=3600)

450

37.4. BASIC LAYOUT

This registers a static resource view which will match any URL that starts with the prefix /static (by virtue of the first argument to add_static view). This will serve up static resources for us from within the static directory of our tutorial package, in this case, via http://localhost:6543/static/ and below (by virtue of the second argument to add_static_view). With this declaration, we’re saying that any URL that starts with /static should go to the static view; any remainder of its path (e.g. the /foo in /static/foo) will be used to compose a path to a static file resource, such as a CSS file.

Using the configurator main also registers a route configuration via the pyramid.config.Configurator.add_route() method that will be used when the URL is /:

config.add_route(’home’, ’/’)

Since this route has a pattern equalling / it is the route that will be matched when the URL / is visted, e.g. http://localhost:6543/.

main next calls the scan method of the configurator, which will recursively scan our tutorial package, looking for @view_config (and other special) decorators. When it finds a @view_config decorator, a view configuration will be registered, which will allow one of our application URLs to be mapped to some code.

config.scan()

Finally, main is finished configuring things, so it uses the pyramid.config.Configurator.make_wsgi_app() method to return a WSGI application:

return config.make_wsgi_app()

37.4.2 View Declarations via views.py

Mapping a route to code that will be executed when a match for the route’s pattern occurs is done by registering a view configuration. Our application uses the pyramid.view.view_config() decorator to map view callables to each route, thereby mapping URL patterns to code.

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

451