File: hellotraversal.rst

package info (click to toggle)
python-pyramid 1.6%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 9,112 kB
  • ctags: 8,169
  • sloc: python: 41,764; makefile: 111; sh: 17
file content (64 lines) | stat: -rw-r--r-- 2,396 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
.. _hello_traversal_chapter:

Hello Traversal World
=====================

.. index::
   single: traversal quick example

Traversal is an alternative to URL dispatch which allows Pyramid applications
to map URLs to code.

If code speaks louder than words, maybe this will help. Here is a single-file
Pyramid application that uses traversal:

.. literalinclude:: hellotraversal.py
   :linenos:

You may notice that this application is intentionally very similar to the
"hello world" application from :doc:`firstapp`.

On lines 5-6, we create a trivial :term:`resource` class that's just a
dictionary subclass.

On lines 8-9, we hard-code a :term:`resource tree` in our :term:`root factory`
function.

On lines 11-13, we define a single :term:`view callable` that can display a
single instance of our ``Resource`` class, passed as the ``context`` argument.

The rest of the file sets up and serves our :app:`Pyramid` WSGI app.  Line 18
is where our view gets configured for use whenever the traversal ends with an
instance of our ``Resource`` class.

Interestingly, there are no URLs explicitly configured in this application.
Instead, the URL space is defined entirely by the keys in the resource tree.

Example requests
----------------

If this example is running on http://localhost:8080, and the user browses to
http://localhost:8080/a/b, Pyramid will call ``get_root(request)`` to get the
root resource, then traverse the tree from there by key; starting from the
root, it will find the child with key ``"a"``, then its child with key ``"b"``;
then use that as the ``context`` argument for calling
``hello_world_of_resources``.

Or, if the user browses to http://localhost:8080/, Pyramid will stop at the
root—the outermost ``Resource`` instance, in this case—and use that as the
``context`` argument to the same view.

Or, if the user browses to a key that doesn't exist in this resource tree, like
http://localhost:8080/xyz or http://localhost:8080/a/b/c/d, the traversal will
end by raising a KeyError, and Pyramid will turn that into a 404 HTTP response.

A more complicated application could have many types of resources, with
different view callables defined for each type, and even multiple views for
each type.

.. seealso::

    Full technical details may be found in :doc:`traversal`.
    
    For more about *why* you might use traversal, see
    :doc:`muchadoabouttraversal`.