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

20.6. WRITING A SCRIPT

$ bin/prequest development.ini /

This will print the body of the response to the console on which it was invoked.

Several options are supported by prequest. These should precede any config file name or URL.

prequest has a -d (aka --display-headers) option which prints the status and headers returned by the server before the output:

$ bin/prequest -d development.ini /

This will print the status, then the headers, then the body of the response to the console.

You can add request header values by using the --header option:

$ bin/prequest --header=Host=example.com development.ini /

Headers are added to the WSGI environment by converting them to their CGI/WSGI equivalents (e.g. Host=example.com will insert the HTTP_HOST header variable as the value example.com). Multiple --header options can be supplied. The special header value content-type sets the CONTENT_TYPE in the WSGI environment.

By default, prequest sends a GET request. You can change this by using the -m (aka --method) option. GET, HEAD, POST and DELETE are currently supported. When you use POST, the standard input of the prequest process is used as the POST body:

$ bin/prequest -mPOST development.ini / < somefile

20.6 Writing a Script

All web applications are, at their hearts, systems which accept a request and return a response. When a request is accepted by a Pyramid application, the system receives state from the request which is later relied on by your application code. For example, one view callable may assume it’s working against a request that has a request.matchdict of a particular composition, while another assumes a different composition of the matchdict.

In the meantime, it’s convenient to be able to write a Python script that can work “in a Pyramid environment”, for instance to update database tables used by your Pyramid application. But a “real” Pyramid

219

20. COMMAND-LINE PYRAMID

environment doesn’t have a completely static state independent of a request; your application (and Pyramid itself) is almost always reliant on being able to obtain information from a request. When you run a Python script that simply imports code from your application and tries to run it, there just is no request data, because there isn’t any real web request. Therefore some parts of your application and some Pyramid APIs will not work.

For this reason, Pyramid makes it possible to run a script in an environment much like the environment produced when a particular request reaches your Pyramid application. This is achieved by using the pyramid.paster.bootstrap() command in the body of your script.

latex-note.png

This feature is new as of Pyramid 1.1.

In the simplest case, pyramid.paster.bootstrap() can be used with a single argument, which accepts the PasteDeploy .ini file representing Pyramid your application configuration as a single argument:

from pyramid.paster import bootstrap

env = bootstrap(’/path/to/my/development.ini’) print env[’request’].route_url(’home’)

pyramid.paster.bootstrap() returns a dictionary containing framework-related information. This dictionary will always contain a request object as its request key.

The following keys are available in the env dictionary returned by pyramid.paster.bootstrap():

request

A pyramid.request.Request object implying the current request state for your script.

app

The WSGI application object generated by bootstrapping.

root

220

20.6. WRITING A SCRIPT

The resource root of your Pyramid application. This is an object generated by the root factory configured in your application.

registry

The application registry of your Pyramid application.

closer

A parameterless callable that can be used to pop an internal Pyramid threadlocal stack (used by pyramid.threadlocal.get_current_registry() and pyramid.threadlocal.get_current_request()) when your scripting job is finished.

Let’s assume that the /path/to/my/development.ini file used in the example above looks like so:

[pipeline:main] pipeline = translogger

another

[filter:translogger]

filter_app_factory = egg:Paste#translogger setup_console_handler = False

logger_name = wsgi

[app:another]

use = egg:MyProject

The

configuration

loaded by the above

bootstrap example will use the

configura-

tion

implied by

the [pipeline:main]

section of your configuration file

by default.

Specifying /path/to/my/development.ini is logically equivalent to specifying /path/to/my/development.ini#main. In this case, we’ll be using a configuration that includes an app object which is wrapped in the Paste “translogger” middleware (which logs requests to the console).

You can also specify a particular section of the PasteDeploy .ini file to load instead of main:

from pyramid.paster import bootstrap

env = bootstrap(’/path/to/my/development.ini#another’) print env[’request’].route_url(’home’)

The above example specifies the another app, pipeline, or composite section of your PasteDeploy configuration file. The app object present in the env dictionary returned by pyramid.paster.bootstrap() will be a Pyramid router.

221

20. COMMAND-LINE PYRAMID

20.6.1 Changing the Request

By default, Pyramid will generate a request object in the env dictionary for the URL http://localhost:80/. This means that any URLs generated by Pyramid during the execution of your script will be anchored here. This is generally not what you want.

So how do we make Pyramid generate the correct URLs?

Assuming that you have a route configured in your application like so:

config.add_route(’verify’, ’/verify/{code}’)

You need to inform the Pyramid environment that the WSGI application is handling requests from a certain base. For example, we want to simulate mounting our application at https://example.com/prefix, to ensure that the generated URLs are correct for our deployment. This can be done by either mutating the resulting request object, or more simply by constructing the desired request and passing it into bootstrap():

from pyramid.paster import bootstrap from pyramid.request import Request

request = Request.blank(’/’, base_url=’https://example.com/prefix’)

env = bootstrap(’/path/to/my/development.ini#another’, request=request) print env[’request’].application_url

# will print ’https://example.com/prefix’

Now you can readily use Pyramid’s APIs for generating URLs:

env[’request’].route_url(’verify’, code=’1337’)

# will return ’https://example.com/prefix/verify/1337’

20.6.2 Cleanup

When your scripting logic finishes, it’s good manners to call the closer callback:

from pyramid.paster import bootstrap

env = bootstrap(’/path/to/my/development.ini’)

# .. do stuff ...

env[’closer’]()

222

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