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

8. URL DISPATCH

1 config.add_route(’idea’, ’ideas/{idea}’, factory=’myproject.resources.Idea’) 2 config.add_view(’myproject.views.idea_view’, route_name=’idea’)

The above route will manufacture an Idea resource as a context, assuming that mypackage.resources.Idea resolves to a class that accepts a request in its __init__. For example:

1

2

3

class Idea(object):

def __init__(self, request): pass

In a more complicated application, this root factory might be a class representing a SQLAlchemy model.

See Route Factories for more details about how to use route factories.

8.5 Matching the Root URL

It’s not entirely obvious how to use a route pattern to match the root URL (“/”). To do so, give the empty string as a pattern in a call to add_route():

1 config.add_route(’root’, ’’)

Or provide the literal string / as the pattern:

1 config.add_route(’root’, ’/’)

8.6 Generating Route URLs

Use the pyramid.request.Request.route_url() method to generate URLs based on route patterns. For example, if you’ve configured a route with the name “foo” and the pattern “{a}/{b}/{c}”, you might do this.

1 url = request.route_url(’foo’, a=’1’, b=’2’, c=’3’)

82

8.6. GENERATING ROUTE URLS

This would return something like the string http://example.com/1/2/3 (at least if the current protocol and hostname implied http://example.com).

To generate only the path portion of a URL from a route, use the pyramid.request.Request.route_path() API instead of route_url().

url = request.route_path(’foo’, a=’1’, b=’2’, c=’3’)

This will return the string /1/2/3 rather than a full URL.

Replacement values passed to route_url or route_path must be Unicode or bytestrings encoded in UTF-8. One exception to this rule exists: if you’re trying to replace a “remainder” match value (a *stararg replacement value), the value may be a tuple containing Unicode strings or UTF-8 strings.

Note that URLs and paths generated by route_path and route_url are always URL-quoted string types (they contain no non-ASCII characters). Therefore, if you’ve added a route like so:

config.add_route(’la’, u’/La Peña/{city}’)

And you later generate a URL using route_path or route_url like so:

url = request.route_path(’la’, city=u’Québec’)

You will wind up with the path encoded to UTF-8 and URL quoted like so:

/La%20Pe%C3%B1a/Qu%C3%A9bec

If you have a *stararg remainder dynamic part of your route pattern:

config.add_route(’abc’, ’a/b/c/*foo’)

And you later generate a URL using route_path or route_url using a string as the replacement value:

url = request.route_path(’abc’, foo=u’Québec/biz’)

The value you pass will be URL-quoted except for embedded slashes in the result:

83

8. URL DISPATCH

/a/b/c/Qu%C3%A9bec/biz

You can get a similar result by passing a tuple composed of path elements:

url = request.route_path(’abc’, foo=(u’Québec’, u’biz’))

Each value in the tuple will be url-quoted and joined by slashes in this case:

/a/b/c/Qu%C3%A9bec/biz

8.7 Static Routes

Routes may be added with a static keyword argument. For example:

1

2

config = Configurator()

config.add_route(’page’, ’/page/{action}’, static=True)

Routes added with a True static keyword argument will never be considered for matching at request time. Static routes are useful for URL generation purposes only. As a result, it is usually nonsensical to provide other non-name and non-pattern arguments to add_route() when static is passed as True, as none of the other arguments will ever be employed. A single exception to this rule is use of the pregenerator argument, which is not ignored when static is True.

latex-note.png

the static argument to add_route() is new as of Pyramid 1.1.

84

8.8.REDIRECTING TO SLASH-APPENDED ROUTES

8.8Redirecting to Slash-Appended Routes

For

behavior like Django’s APPEND_SLASH=True, use the append_slash

argument

to

pyramid.config.Configurator.add_notfound_view() or the

equivalent

append_slash argument to the pyramid.view.notfound_view_config decorator.

Adding append_slash=True is a way to automatically redirect requests where the URL lacks a trailing slash, but requires one to match the proper route. When configured, along with at least one other route in your application, this view will be invoked if the value of PATH_INFO does not already end in a slash, and if the value of PATH_INFO plus a slash matches any route’s pattern. In this case it does an HTTP redirect to the slash-appended PATH_INFO.

Let’s use an example. If the following routes are configured in your application:

1

from pyramid.httpexceptions import HTTPNotFound

2

 

3

def notfound(request):

4

return HTTPNotFound(’Not found, bro.’)

5

 

6

def no_slash(request):

7

return Response(’No slash’)

8

 

9

def has_slash(request):

10

return Response(’Has slash’)

11

12def main(g, **settings):

13config = Configurator()

14config.add_route(’noslash’, ’no_slash’)

15config.add_route(’hasslash’, ’has_slash/’)

16config.add_view(no_slash, route_name=’noslash’)

17config.add_view(has_slash, route_name=’hasslash’)

18config.add_notfound_view(notfound, append_slash=True)

If a request enters the application with the PATH_INFO value of /no_slash, the first route will match and the browser will show “No slash”. However, if a request enters the application with the PATH_INFO value of /no_slash/, no route will match, and the slash-appending not found view will not find a matching route with an appended slash. As a result, the notfound view will be called and it will return a “Not found, bro.” body.

If a request enters the application with the PATH_INFO value of /has_slash/, the second route will match. If a request enters the application with the PATH_INFO value of /has_slash, a route will be found by the slash-appending not found view. An HTTP redirect to /has_slash/ will be returned to the user’s browser. As a result, the notfound view will never actually be called.

The following application uses the pyramid.view.notfound_view_config and pyramid.view.view_config decorators and a scan to do exactly the same job:

85

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