Debian Codegraph @

docs/source/routing.rst

raw
1 .. _routing:
2
3 Controllers and Routing
4 =======================
5
6 Pecan uses a routing strategy known as **object-dispatch** to map an
7 HTTP request to a controller, and then the method to call.
8 Object-dispatch begins by splitting the path into a list of components
9 and then walking an object path, starting at the root controller. You
10 can imagine your application's controllers as a tree of objects
11 (branches of the object tree map directly to URL paths).
12
13 Let's look at a simple bookstore application:
14
15 ::
16
17 from pecan import expose
18
19 class BooksController(object):
20 @expose()
21 def index(self):
22 return "Welcome to book section."
23
24 @expose()
25 def bestsellers(self):
26 return "We have 5 books in the top 10."
27
28 class CatalogController(object):
29 @expose()
30 def index(self):
31 return "Welcome to the catalog."
32
33 books = BooksController()
34
35 class RootController(object):
36 @expose()
37 def index(self):
38 return "Welcome to store.example.com!"
39
40 @expose()
41 def hours(self):
42 return "Open 24/7 on the web."
43
44 catalog = CatalogController()
45
46 A request for ``/catalog/books/bestsellers`` from the online store would
47 begin with Pecan breaking the request up into ``catalog``, ``books``, and
48 ``bestsellers``. Next, Pecan would lookup ``catalog`` on the root
49 controller. Using the ``catalog`` object, Pecan would then lookup
50 ``books``, followed by ``bestsellers``. What if the URL ends in a slash?
51 Pecan will check for an ``index`` method on the last controller object.
52
53 To illustrate further, the following paths:
54
55 ::
56
57    └── /
58    ├── /hours
59    └── /catalog
60    └── /catalog/books
61    └── /catalog/books/bestsellers
62
63 route to the following controller methods:
64
65 ::
66
67    └── RootController.index
68    ├── RootController.hours
69    └── CatalogController.index
70    └── BooksController.index
71    └── BooksController.bestsellers
72
73
74 Exposing Controllers
75 --------------------
76
77 You tell Pecan which methods in a class are publically-visible via
78 :func:`~pecan.decorators.expose`. If a method is *not* decorated with
79 :func:`~pecan.decorators.expose`, Pecan will never route a request to it.
80
81 :func:`~pecan.decorators.expose` can be used in a variety of ways. The
82 simplest case involves passing no arguments. In this scenario, the controller
83 returns a string representing the HTML response body.
84
85 ::
86
87 from pecan import expose
88
89 class RootController(object):
90 @expose()
91 def hello(self):
92 return 'Hello World'
93
94
95 A more common use case is to :ref:`specify a template and a namespace
96 <templates>`::
97
98 from pecan import expose
99
100 class RootController(object):
101 @expose('html_template.mako')
102 def hello(self):
103 return {'msg': 'Hello!'}
104
105 ::
106
107 <!-- html_template.mako -->
108 <html>
109 <body>${msg}</body>
110 </html>
111
112 Pecan also has built-in support for a special :ref:`JSON renderer
113 <expose_json>`, which translates template namespaces into rendered JSON text::
114
115 from pecan import expose
116
117 class RootController(object):
118 @expose('json')
119 def hello(self):
120 return {'msg': 'Hello!'}
121
122 :func:`~pecan.decorators.expose` calls can also be stacked, which allows you to
123 serialize content differently depending on how the content is requested::
124
125 from pecan import expose
126
127 class RootController(object):
128 @expose('json')
129 @expose('text_template.mako', content_type='text/plain')
130 @expose('html_template.mako')
131 def hello(self):
132 return {'msg': 'Hello!'}
133
134 You'll notice that we called :func:`~pecan.decorators.expose` three times, with
135 different arguments.
136
137 ::
138
139 @expose('json')
140
141 The first tells Pecan to serialize the response namespace using JSON
142 serialization when the client requests ``/hello.json`` or if an
143 ``Accept: application/json`` header is present.
144
145 ::
146
147 @expose('text_template.mako', content_type='text/plain')
148
149 The second tells Pecan to use the ``text_template.mako`` template file when the
150 client requests ``/hello.txt`` or asks for text/plain via an ``Accept`` header.
151
152 ::
153
154 @expose('html_template.mako')
155
156 The third tells Pecan to use the ``html_template.mako`` template file when the
157 client requests ``/hello.html``. If the client requests ``/hello``, Pecan will
158 use the ``text/html`` content type by default; in the absense of an explicit
159 content type, Pecan assumes the client wants HTML.
160
161 .. seealso::
162
163 * :ref:`pecan_decorators`
164
165
166 Specifying Explicit Path Segments
167 ---------------------------------
168
169 Occasionally, you may want to use a path segment in your routing that doesn't
170 work with Pecan's declarative approach to routing because of restrictions in
171 Python's syntax. For example, if you wanted to route for a path that includes
172 dashes, such as ``/some-path/``, the following is *not* valid Python::
173
174
175 class RootController(object):
176
177 @pecan.expose()
178 def some-path(self):
179 return dict()
180
181 To work around this, pecan allows you to specify an explicit path segment in
182 the :func:`~pecan.decorators.expose` decorator::
183
184 class RootController(object):
185
186 @pecan.expose(route='some-path')
187 def some_path(self):
188 return dict()
189
190 In this example, the pecan application will reply with an ``HTTP 200`` for
191 requests made to ``/some-path/``, but requests made to ``/some_path/`` will
192 yield an ``HTTP 404``.
193
194 :func:`~pecan.routing.route` can also be used explicitly as an alternative to
195 the ``route`` argument in :func:`~pecan.decorators.expose`::
196
197 class RootController(object):
198
199 @pecan.expose()
200 def some_path(self):
201 return dict()
202
203 pecan.route('some-path', RootController.some_path)
204
205 Routing to child controllers can be handled simliarly by utilizing
206 :func:`~pecan.routing.route`::
207
208
209 class ChildController(object):
210
211 @pecan.expose()
212 def child(self):
213 return dict()
214
215 class RootController(object):
216 pass
217
218 pecan.route(RootController, 'child-path', ChildController())
219
220 In this example, the pecan application will reply with an ``HTTP 200`` for
221 requests made to ``/child-path/child/``.
222
223
224 Routing Based on Request Method
225 -------------------------------
226
227 The ``generic`` argument to :func:`~pecan.decorators.expose` provides support for overloading URLs
228 based on the request method. In the following example, the same URL can be
229 serviced by two different methods (one for handling HTTP ``GET``, another for
230 HTTP ``POST``) using `generic controllers`:
231
232 ::
233
234 from pecan import expose
235
236
237 class RootController(object):
238
239 # HTTP GET /
240 @expose(generic=True, template='json')
241 def index(self):
242 return dict()
243
244 # HTTP POST /
245 @index.when(method='POST', template='json')
246 def index_POST(self, **kw):
247 uuid = create_something()
248 return dict(uuid=uuid)
249
250
251 Pecan's Routing Algorithm
252 -------------------------
253
254 Sometimes, the standard object-dispatch routing isn't adequate to properly
255 route a URL to a controller. Pecan provides several ways to short-circuit
256 the object-dispatch system to process URLs with more control, including the
257 special :func:`_lookup`, :func:`_default`, and :func:`_route` methods. Defining
258 these methods on your controller objects provides additional flexibility for
259 processing all or part of a URL.
260
261
262 Routing to Subcontrollers with ``_lookup``
263 ------------------------------------------
264
265 The :func:`_lookup` special method provides a way to process a portion of a URL,
266 and then return a new controller object to route to for the remainder.
267
268 A :func:`_lookup` method may accept one or more arguments, segments
269 of the URL path to be processed (split on
270 ``/``). :func:`_lookup` should also take variable positional arguments
271 representing the rest of the path, and it should include any portion
272 of the path it does not process in its return value. The example below
273 uses a ``*remainder`` list which will be passed to the returned
274 controller when the object-dispatch algorithm continues.
275
276 In addition to being used for creating controllers dynamically,
277 :func:`_lookup` is called as a last resort, when no other controller
278 method matches the URL and there is no :func:`_default` method.
279
280 ::
281
282 from pecan import expose, abort
283 from somelib import get_student_by_name
284
285 class StudentController(object):
286 def __init__(self, student):
287 self.student = student
288
289 @expose()
290 def name(self):
291 return self.student.name
292
293 class RootController(object):
294 @expose()
295 def _lookup(self, primary_key, *remainder):
296 student = get_student_by_primary_key(primary_key)
297 if student:
298 return StudentController(student), remainder
299 else:
300 abort(404)
301
302 An HTTP GET request to ``/8/name`` would return the name of the student
303 where ``primary_key == 8``.
304
305
306 Falling Back with ``_default``
307 ------------------------------
308
309 The :func:`_default` method is called as a last resort when no other controller
310 methods match the URL via standard object-dispatch.
311
312 ::
313
314 from pecan import expose
315
316 class RootController(object):
317 @expose()
318 def english(self):
319 return 'hello'
320
321 @expose()
322 def french(self):
323 return 'bonjour'
324
325 @expose()
326 def _default(self):
327 return 'I cannot say hello in that language'
328
329
330 In the example above, a request to ``/spanish`` would route to
331 :func:`RootController._default`.
332
333
334 Defining Customized Routing with ``_route``
335 -------------------------------------------
336
337 The :func:`_route` method allows a controller to completely override the routing
338 mechanism of Pecan. Pecan itself uses the :func:`_route` method to implement its
339 :class:`~pecan.rest.RestController`. If you want to design an alternative
340 routing system on top of Pecan, defining a base controller class that defines
341 a :func:`_route` method will enable you to have total control.
342
343
344 Interacting with the Request and Response Object
345 ================================================
346
347 For every HTTP request, Pecan maintains a :ref:`thread-local reference
348 <contextlocals>` to the request and response object, ``pecan.request`` and
349 ``pecan.response``. These are instances of :class:`pecan.Request`
350 and :class:`pecan.Response`, respectively, and can be interacted with
351 from within Pecan controller code::
352
353 @pecan.expose()
354 def login(self):
355 assert pecan.request.path == '/login'
356 username = pecan.request.POST.get('username')
357 password = pecan.request.POST.get('password')
358
359 pecan.response.status = 403
360 pecan.response.text = 'Bad Login!'
361
362 While Pecan abstracts away much of the need to interact with these objects
363 directly, there may be situations where you want to access them, such as:
364
365 * Inspecting components of the URI
366 * Determining aspects of the request, such as the user's IP address, or the
367 referer header
368 * Setting specific response headers
369 * Manually rendering a response body
370
371
372 Specifying a Custom Response
373 ----------------------------
374
375 Set a specific HTTP response code (such as ``203 Non-Authoritative Information``) by
376 modifying the ``status`` attribute of the response object.
377
378 ::
379
380 from pecan import expose, response
381
382 class RootController(object):
383
384 @expose('json')
385 def hello(self):
386 response.status = 203
387 return {'foo': 'bar'}
388
389 Use the utility function :func:`~pecan.core.abort` to raise HTTP errors.
390
391 ::
392
393 from pecan import expose, abort
394
395 class RootController(object):
396
397 @expose('json')
398 def hello(self):
399 abort(404)
400
401
402 :func:`~pecan.core.abort` raises an instance of
403 :class:`~webob.exc.WSGIHTTPException` which is used by Pecan to render
404 default response bodies for HTTP errors. This exception is stored in
405 the WSGI request environ at ``pecan.original_exception``, where it
406 can be accessed later in the request cycle (by, for example, other
407 middleware or :ref:`errors`).
408
409 If you'd like to return an explicit response, you can do so using
410 :class:`~pecan.core.Response`:
411
412 ::
413
414 from pecan import expose, Response
415
416 class RootController(object):
417
418 @expose()
419 def hello(self):
420 return Response('Hello, World!', 202)
421
422
423 Extending Pecan's Request and Response Object
424 ---------------------------------------------
425
426 The request and response implementations provided by WebOb are powerful, but
427 at times, it may be useful to extend application-specific behavior onto your
428 request and response (such as specialized parsing of request headers or
429 customized response body serialization). To do so, define custom classes that
430 inherit from ``pecan.Request`` and ``pecan.Response``, respectively::
431
432 class MyRequest(pecan.Request):
433 pass
434
435 class MyResponse(pecan.Response):
436 pass
437
438 and modify your application configuration to use them::
439
440 from myproject import MyRequest, MyResponse
441
442 app = {
443 'root' : 'project.controllers.root.RootController',
444 'modules' : ['project'],
445 'static_root' : '%(confdir)s/public',
446 'template_path' : '%(confdir)s/project/templates',
447 'request_cls': MyRequest,
448 'response_cls': MyResponse
449 }
450
451
452 Mapping Controller Arguments
453 ----------------------------
454
455 In Pecan, HTTP ``GET`` and ``POST`` variables that are not consumed
456 during the routing process can be passed onto the controller method as
457 arguments.
458
459 Depending on the signature of the method, these arguments can be mapped
460 explicitly to arguments:
461
462 ::
463
464 from pecan import expose
465
466 class RootController(object):
467 @expose()
468 def index(self, arg):
469 return arg
470
471 @expose()
472 def kwargs(self, **kwargs):
473 return str(kwargs)
474
475 ::
476
477 $ curl http://localhost:8080/?arg=foo
478 foo
479 $ curl http://localhost:8080/kwargs?a=1&b=2&c=3
480 {u'a': u'1', u'c': u'3', u'b': u'2'}
481
482 or can be consumed positionally:
483
484 ::
485
486 from pecan import expose
487
488 class RootController(object):
489 @expose()
490 def args(self, *args):
491 return ','.join(args)
492
493 ::
494
495 $ curl http://localhost:8080/args/one/two/three
496 one,two,three
497
498 The same effect can be achieved with HTTP ``POST`` body variables:
499
500 ::
501
502 from pecan import expose
503
504 class RootController(object):
505 @expose()
506 def index(self, arg):
507 return arg
508
509 ::
510
511 $ curl -X POST "http://localhost:8080/" -H "Content-Type: application/x-www-form-urlencoded" -d "arg=foo"
512 foo
513
514
515 Static File Serving
516 -------------------
517
518 Because Pecan gives you direct access to the underlying
519 :class:`~webob.request.Request`, serving a static file download is as simple as
520 setting the WSGI ``app_iter`` and specifying the content type::
521
522 import os
523 from random import choice
524
525 from webob.static import FileIter
526
527 from pecan import expose, response
528
529
530 class RootController(object):
531
532 @expose(content_type='image/gif')
533 def gifs(self):
534 filepath = choice((
535 "/path/to/funny/gifs/catdance.gif",
536 "/path/to/funny/gifs/babydance.gif",
537 "/path/to/funny/gifs/putindance.gif"
538 ))
539 f = open(filepath, 'rb')
540 response.app_iter = FileIter(f)
541 response.headers[
542 'Content-Disposition'
543 ] = 'attachment; filename="%s"' % os.path.basename(f.name)
544
545 If you don't know the content type ahead of time (for example, if you're
546 retrieving files and their content types from a data store), you can specify
547 it via ``response.headers`` rather than in the :func:`~pecan.decorators.expose`
548 decorator::
549
550 import os
551 from mimetypes import guess_type
552
553 from webob.static import FileIter
554
555 from pecan import expose, response
556
557
558 class RootController(object):
559
560 @expose()
561 def download(self):
562 f = open('/path/to/some/file', 'rb')
563 response.app_iter = FileIter(f)
564 response.headers['Content-Type'] = guess_type(f.name)
565 response.headers[
566 'Content-Disposition'
567 ] = 'attachment; filename="%s"' % os.path.basename(f.name)
568
569
570 Handling File Uploads
571 ---------------------
572
573 Pecan makes it easy to handle file uploads via standard multipart forms. Simply
574 define your form with a file input:
575
576 .. code-block:: html
577
578 <form action="/upload" method="POST" enctype="multipart/form-data">
579 <input type="file" name="file" />
580 <button type="submit">Upload</button>
581 </form>
582
583 You can then read the uploaded file off of the request object in your
584 application's controller:
585
586 ::
587
588 from pecan import expose, request
589
590 class RootController(object):
591 @expose()
592 def upload(self):
593 assert isinstance(request.POST['file'], cgi.FieldStorage)
594 data = request.POST['file'].file.read()
595
596
597 Thread-Safe Per-Request Storage
598 -------------------------------
599
600 For convenience, Pecan provides a Python dictionary on every request which can
601 be accessed and modified in a thread-safe manner throughout the life-cycle of
602 an individual request::
603
604 pecan.request.context['current_user'] = some_user
605 print pecan.request.context.items()
606
607 This is particularly useful in situations where you want to store
608 metadata/context about a request (e.g., in middleware, or per-routing hooks)
609 and access it later (e.g., in controller code).
610
611 For more fine-grained control of the request, the underlying WSGI environ for
612 a given Pecan request can be accessed and modified via
613 ``pecan.request.environ``.
614
615
616 Helper Functions
617 ----------------
618
619 Pecan also provides several useful helper functions for moving between
620 different routes. The :func:`~pecan.core.redirect` function allows you to issue
621 internal or ``HTTP 302`` redirects.
622
623 .. seealso::
624
625 The :func:`redirect` utility, along with several other useful
626 helpers, are documented in :ref:`pecan_core`.
627
628
629 Determining the URL for a Controller
630 ------------------------------------
631 Given the ability for routing to be drastically changed at runtime, it is not
632 always possible to correctly determine a mapping between a controller method
633 and a URL.
634
635 For example, in the following code that makes use of :func:`_lookup` to alter
636 the routing depending on a condition::
637
638
639 from pecan import expose, abort
640 from somelib import get_user_region
641
642
643 class DefaultRegionController(object):
644
645 @expose()
646 def name(self):
647 return "Default Region"
648
649 class USRegionController(object):
650
651 @expose()
652 def name(self):
653 return "US Region"
654
655 class RootController(object):
656 @expose()
657 def _lookup(self, user_id, *remainder):
658 if get_user_region(user_id) == 'us':
659 return USRegionController(), remainder
660 else:
661 return DefaultRegionController(), remainder
662
663 This logic depends on the geolocation of a given user and returning
664 a completely different class given the condition. A helper to determine what
665 URL ``USRegionController.name`` belongs to would fail to do it correctly.