Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 579 lines (441 sloc) 24.476 kB
178623b Tweaks.
Chris McDonough authored
1 .. _traversal_chapter:
2
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
3 Traversal
4 =========
5
97b64d3 @slinkp Hello world with traversal, linked from various places; plus some 'wh…
slinkp authored
6 This chapter explains the technical details of how traversal works in
7 Pyramid.
8
9 For a quick example, see :doc:`hellotraversal`.
10
11 For more about *why* you might use traversal, see :doc:`muchadoabouttraversal`.
12
70dacbb @mcdonc get rid of UNIX user analogy
mcdonc authored
13 A :term:`traversal` uses the URL (Universal Resource Locator) to find a
f4c5f1a @caseman add Much ado about traversal chapter from Rob Miller, with light adap…
caseman authored
14 :term:`resource` located in a :term:`resource tree`, which is a set of
15 nested dictionary-like objects. Traversal is done by using each segment
16 of the path portion of the URL to navigate through the :term:`resource
17 tree`. You might think of this as looking up files and directories in a
18 file system. Traversal walks down the path until it finds a published
f69e198 @caseman clarify opening paragraph
caseman authored
19 resource, analogous to a file system "directory" or "file". The
20 resource found as the result of a traversal becomes the
21 :term:`context` of the :term:`request`. Then, the :term:`view lookup`
83940c9 @Cito Some typos, better quoting in Traversal docs.
Cito authored
22 subsystem is used to find some view code willing to "publish" this
f69e198 @caseman clarify opening paragraph
caseman authored
23 resource by generating a :term:`response`.
70dacbb @mcdonc get rid of UNIX user analogy
mcdonc authored
24
f4c5f1a @caseman add Much ado about traversal chapter from Rob Miller, with light adap…
caseman authored
25 Using :term:`Traversal` to map a URL to code is optional. It is often
26 less easy to understand than :term:`URL dispatch`, so if you're a rank
27 beginner, it probably makes sense to use URL dispatch to map URLs to
f4e5b83 @caseman remove stray quote
caseman authored
28 code instead of traversal. In that case, you can skip this chapter.
f4c5f1a @caseman add Much ado about traversal chapter from Rob Miller, with light adap…
caseman authored
29
70dacbb @mcdonc get rid of UNIX user analogy
mcdonc authored
30 .. index::
31 single: traversal details
32
33 Traversal Details
34 -----------------
35
2ceb1f3 @caseman simplify/clarify
caseman authored
36 :term:`Traversal` is dependent on information in a :term:`request`
37 object. Every :term:`request` object contains URL path information in
38 the ``PATH_INFO`` portion of the :term:`WSGI` environment. The
39 ``PATH_INFO`` string is the portion of a request's URL following the
40 hostname and port number, but before any query string elements or
780999e @mcdonc context finding -> resource location
mcdonc authored
41 fragment element. For example the ``PATH_INFO`` portion of the URL
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
42 ``http://example.com:8080/a/b/c?foo=1`` is ``/a/b/c``.
590fe7c Massive overhaul to deal with the reality that we don't map URLs dire…
Chris McDonough authored
43
234c0d6 @caseman reword for clarity
caseman authored
44 Traversal treats the ``PATH_INFO`` segment of a URL as a sequence of
45 path segments. For example, the ``PATH_INFO`` string ``/a/b/c`` is
46 converted to the sequence ``['a', 'b', 'c']``.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
47
234c0d6 @caseman reword for clarity
caseman authored
48 This path sequence is then used to descend through the :term:`resource
49 tree`, looking up a resource for each path segment. Each lookup uses the
50 ``__getitem__`` method of a resource in the tree.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
51
52 For example, if the path info sequence is ``['a', 'b', 'c']``:
53
1dff47e @caseman clarify traversal details
caseman authored
54 - :term:`Traversal` starts by acquiring the :term:`root` resource of the
55 application by calling the :term:`root factory`. The :term:`root factory`
56 can be configured to return whatever object is appropriate as the
57 traversal root of your application.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
58
83940c9 @Cito Some typos, better quoting in Traversal docs.
Cito authored
59 - Next, the first element (``'a'``) is popped from the path segment
1dff47e @caseman clarify traversal details
caseman authored
60 sequence and is used as a key to lookup the corresponding resource
61 in the root. This invokes the root resource's ``__getitem__`` method
e2cd788 @Cito Fixed quote chars.
Cito authored
62 using that value (``'a'``) as an argument.
1dff47e @caseman clarify traversal details
caseman authored
63
83940c9 @Cito Some typos, better quoting in Traversal docs.
Cito authored
64 - If the root resource "contains" a resource with key ``'a'``, its
1dff47e @caseman clarify traversal details
caseman authored
65 ``__getitem__`` method will return it. The :term:`context` temporarily
66 becomes the "A" resource.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
67
83940c9 @Cito Some typos, better quoting in Traversal docs.
Cito authored
68 - The next segment (``'b'``) is popped from the path sequence, and the "A"
69 resource's ``__getitem__`` is called with that value (``'b'``) as an
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
70 argument; we'll presume it succeeds.
71
1dff47e @caseman clarify traversal details
caseman authored
72 - The "A" resource's ``__getitem__`` returns another resource, which
73 we'll call "B". The :term:`context` temporarily becomes the "B"
74 resource.
75
76 Traversal continues until the path segment sequence is exhausted or a
77 path element cannot be resolved to a resource. In either case, the
78 :term:`context` resource is the last object that the traversal
79 successfully resolved. If any resource found during traversal lacks a
80 ``__getitem__`` method, or if its ``__getitem__`` method raises a
81 :exc:`KeyError`, traversal ends immediately, and that resource becomes
82 the :term:`context`.
590fe7c Massive overhaul to deal with the reality that we don't map URLs dire…
Chris McDonough authored
83
f4b5b97 @caseman XXX try to clearly explain how the view name is derived during traver…
caseman authored
84 The results of a :term:`traversal` also include a :term:`view name`. If
85 traversal ends before the path segment sequence is exhausted, the
86 :term:`view name` is the *next* remaining path segment element. If the
87 :term:`traversal` expends all of the path segments, then the :term:`view
83940c9 @Cito Some typos, better quoting in Traversal docs.
Cito authored
88 name` is the empty string (``''``).
590fe7c Massive overhaul to deal with the reality that we don't map URLs dire…
Chris McDonough authored
89
f4c5f1a @caseman add Much ado about traversal chapter from Rob Miller, with light adap…
caseman authored
90 The combination of the context resource and the :term:`view name` found
91 via traversal is used later in the same request by the :term:`view
92 lookup` subsystem to find a :term:`view callable`. How :app:`Pyramid`
8a1b50b @caseman Split view chapter, move view config after templates, some reordering…
caseman authored
93 performs view lookup is explained within the :ref:`view_config_chapter`
f4c5f1a @caseman add Much ado about traversal chapter from Rob Miller, with light adap…
caseman authored
94 chapter.
9302a2a @pauleveritt Text cleanup in traversal.
pauleveritt authored
95
8c56ae4 - Added manual index entries to generated index.
Chris McDonough authored
96 .. index::
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
97 single: object tree
98 single: traversal tree
99 single: resource tree
8c56ae4 - Added manual index entries to generated index.
Chris McDonough authored
100
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
101 .. _the_resource_tree:
b538144 Make the hybrid chapter represent reality.
Chris McDonough authored
102
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
103 The Resource Tree
104 -----------------
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
105
ad838b5 @caseman rework opening explanation of the resource tree for clarity
caseman authored
106 The resource tree is a set of nested dictionary-like resource objects
107 that begins with a :term:`root` resource. In order to use
108 :term:`traversal` to resolve URLs to code, your application must supply
109 a :term:`resource tree` to :app:`Pyramid`.
110
111 In order to supply a root resource for an application the :app:`Pyramid`
112 :term:`Router` is configured with a callback known as a :term:`root
113 factory`. The root factory is supplied by the application, at startup
114 time, as the ``root_factory`` argument to the :term:`Configurator`.
115
116 The root factory is a Python callable that accepts a :term:`request`
117 object, and returns the root object of the :term:`resource tree`. A
118 function, or class is typically used as an application's root factory.
119 Here's an example of a simple root factory class:
c44a950 Stray text.
Chris McDonough authored
120
121 .. code-block:: python
122 :linenos:
123
124 class Root(dict):
125 def __init__(self, request):
126 pass
127
70dacbb @mcdonc get rid of UNIX user analogy
mcdonc authored
128 Here's an example of using this root factory within startup configuration, by
129 passing it to an instance of a :term:`Configurator` named ``config``:
c44a950 Stray text.
Chris McDonough authored
130
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
131 .. code-block:: python
132 :linenos:
133
c44a950 Stray text.
Chris McDonough authored
134 config = Configurator(root_factory=Root)
135
419b226 @caseman rework paragraphs discussifng root factot config
caseman authored
136 The ``root_factory`` argument to the
70acd25 @mcdonc module name contractions
mcdonc authored
137 :class:`~pyramid.config.Configurator` constructor registers this root
419b226 @caseman rework paragraphs discussifng root factot config
caseman authored
138 factory to be called to generate a root resource whenever a request
139 enters the application. The root factory registered this way is also
140 known as the global root factory. A root factory can alternately be
141 passed to the ``Configurator`` as a :term:`dotted Python name` which can
142 refer to a root factory defined in a different module.
21a4807 Tweak.
Chris McDonough authored
143
fd5ae92 @mcdonc - All references to Pyramid-the-application were changed from :mod:`p…
mcdonc authored
144 If no :term:`root factory` is passed to the :app:`Pyramid`
419b226 @caseman rework paragraphs discussifng root factot config
caseman authored
145 :term:`Configurator` constructor, or if the ``root_factory`` value
146 specified is ``None``, a *default* root factory is used. The default
147 root factory always returns a resource that has no child resources; it
148 is effectively empty.
149
150 Usually a root factory for a traversal-based application will be more
151 complicated than the above ``Root`` class; in particular it may be
152 associated with a database connection or another persistence mechanism.
c44a950 Stray text.
Chris McDonough authored
153
590fe7c Massive overhaul to deal with the reality that we don't map URLs dire…
Chris McDonough authored
154 .. sidebar:: Emulating the Default Root Factory
155
450006e @mcdonc wording
mcdonc authored
156 For purposes of understanding the default root factory better, we'll note
157 that you can emulate the default root factory by using this code as an
158 explicit root factory in your application setup:
590fe7c Massive overhaul to deal with the reality that we don't map URLs dire…
Chris McDonough authored
159
160 .. code-block:: python
161 :linenos:
162
163 class Root(object):
164 def __init__(self, request):
165 pass
166
167 config = Configurator(root_factory=Root)
168
169 The default root factory is just a really stupid object that has no
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
170 behavior or state. Using :term:`traversal` against an application that
780999e @mcdonc context finding -> resource location
mcdonc authored
171 uses the resource tree supplied by the default root resource is not very
172 interesting, because the default root resource has no children. Its
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
173 availability is more useful when you're developing an application using
174 :term:`URL dispatch`.
175
a5ffd62 @mcdonc model->resource; make docs render without warnings
mcdonc authored
176 .. note::
177
178 If the items contained within the resource tree are "persistent" (they
179 have state that lasts longer than the execution of a single process), they
180 become analogous to the concept of :term:`domain model` objects used by
181 many other frameworks.
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
182
183 The resource tree consists of *container* resources and *leaf* resources.
184 There is only one difference between a *container* resource and a *leaf*
70dacbb @mcdonc get rid of UNIX user analogy
mcdonc authored
185 resource: *container* resources possess a ``__getitem__`` method (making it
186 "dictionary-like") while *leaf* resources do not. The ``__getitem__`` method
187 was chosen as the signifying difference between the two types of resources
188 because the presence of this method is how Python itself typically determines
189 whether an object is "containerish" or not (dictionary objects are
190 "containerish").
39b8b92 More balance between URL dispatch and traversal.
Chris McDonough authored
191
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
192 Each container resource is presumed to be willing to return a child resource
2bec99e Refactor.
Chris McDonough authored
193 or raise a ``KeyError`` based on a name passed to its ``__getitem__``.
39b8b92 More balance between URL dispatch and traversal.
Chris McDonough authored
194
450006e @mcdonc wording
mcdonc authored
195 Leaf-level instances must not have a ``__getitem__``. If instances that
196 you'd like to be leaves already happen to have a ``__getitem__`` through some
197 historical inequity, you should subclass these resource types and cause their
198 ``__getitem__`` methods to simply raise a ``KeyError``. Or just disuse them
199 and think up another strategy.
39b8b92 More balance between URL dispatch and traversal.
Chris McDonough authored
200
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
201 Usually, the traversal root is a *container* resource, and as such it
202 contains other resources. However, it doesn't *need* to be a container.
203 Your resource tree can be as shallow or as deep as you require.
39b8b92 More balance between URL dispatch and traversal.
Chris McDonough authored
204
780999e @mcdonc context finding -> resource location
mcdonc authored
205 In general, the resource tree is traversed beginning at its root resource
206 using a sequence of path elements described by the ``PATH_INFO`` of the
207 current request; if there are path segments, the root resource's
208 ``__getitem__`` is called with the next path segment, and it is expected to
209 return another resource. The resulting resource's ``__getitem__`` is called
210 with the very next path segment, and it is expected to return another
211 resource. This happens *ad infinitum* until all path segments are exhausted.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
212
213 .. index::
214 single: traversal algorithm
c5f24b2 Prep for b1
Chris McDonough authored
215 single: view lookup
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
216
217 .. _traversal_algorithm:
218
219 The Traversal Algorithm
220 -----------------------
221
450006e @mcdonc wording
mcdonc authored
222 This section will attempt to explain the :app:`Pyramid` traversal algorithm.
223 We'll provide a description of the algorithm, a diagram of how the algorithm
224 works, and some example traversal scenarios that might help you understand
225 how the algorithm operates against a specific resource tree.
226
8a1b50b @caseman Split view chapter, move view config after templates, some reordering…
caseman authored
227 We'll also talk a bit about :term:`view lookup`. The
228 :ref:`view_config_chapter` chapter discusses :term:`view lookup` in
229 detail, and it is the canonical source for information about views.
230 Technically, :term:`view lookup` is a :app:`Pyramid` subsystem that is
231 separated from traversal entirely. However, we'll describe the
232 fundamental behavior of view lookup in the examples in the next few
233 sections to give you an idea of how traversal and view lookup cooperate,
234 because they are almost always used together.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
235
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
236 .. index::
c5f24b2 Prep for b1
Chris McDonough authored
237 single: view name
238 single: context
239 single: subpath
240 single: root factory
241 single: default view
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
242
c5f24b2 Prep for b1
Chris McDonough authored
243 A Description of The Traversal Algorithm
244 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
245
b1f5e62 @mcdonc nonsensical mod
mcdonc authored
246 When a user requests a page from your traversal-powered application, the
247 system uses this algorithm to find a :term:`context` resource and a
450006e @mcdonc wording
mcdonc authored
248 :term:`view name`.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
249
fd5ae92 @mcdonc - All references to Pyramid-the-application were changed from :mod:`p…
mcdonc authored
250 #. The request for the page is presented to the :app:`Pyramid`
450006e @mcdonc wording
mcdonc authored
251 :term:`router` in terms of a standard :term:`WSGI` request, which is
252 represented by a WSGI environment and a WSGI ``start_response`` callable.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
253
2bec99e Refactor.
Chris McDonough authored
254 #. The router creates a :term:`request` object based on the WSGI
255 environment.
c6e58bb - Add startup process docs.
Chris McDonough authored
256
450006e @mcdonc wording
mcdonc authored
257 #. The :term:`root factory` is called with the :term:`request`. It returns
258 a :term:`root` resource.
21a4807 Tweak.
Chris McDonough authored
259
450006e @mcdonc wording
mcdonc authored
260 #. The router uses the WSGI environment's ``PATH_INFO`` information to
261 determine the path segments to traverse. The leading slash is stripped
262 off ``PATH_INFO``, and the remaining path segments are split on the slash
263 character to form a traversal sequence.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
264
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
265 The traversal algorithm by default attempts to first URL-unquote and then
266 Unicode-decode each path segment derived from ``PATH_INFO`` from its
267 natural byte string (``str`` type) representation. URL unquoting is
268 performed using the Python standard library ``urllib.unquote`` function.
269 Conversion from a URL-decoded string into Unicode is attempted using the
270 UTF-8 encoding. If any URL-unquoted path segment in ``PATH_INFO`` is not
271 decodeable using the UTF-8 decoding, a :exc:`TypeError` is raised. A
272 segment will be fully URL-unquoted and UTF8-decoded before it is passed
83940c9 @Cito Some typos, better quoting in Traversal docs.
Cito authored
273 in to the ``__getitem__`` of any resource during traversal.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
274
450006e @mcdonc wording
mcdonc authored
275 Thus, a request with a ``PATH_INFO`` variable of ``/a/b/c`` maps to the
276 traversal sequence ``[u'a', u'b', u'c']``.
c6e58bb - Add startup process docs.
Chris McDonough authored
277
780999e @mcdonc context finding -> resource location
mcdonc authored
278 #. :term:`Traversal` begins at the root resource returned by the root
279 factory. For the traversal sequence ``[u'a', u'b', u'c']``, the root
83940c9 @Cito Some typos, better quoting in Traversal docs.
Cito authored
280 resource's ``__getitem__`` is called with the name ``'a'``. Traversal
780999e @mcdonc context finding -> resource location
mcdonc authored
281 continues through the sequence. In our example, if the root resource's
282 ``__getitem__`` called with the name ``a`` returns a resource (aka
83940c9 @Cito Some typos, better quoting in Traversal docs.
Cito authored
283 resource "A"), that resource's ``__getitem__`` is called with the name
284 ``'b'``. If resource "A" returns a resource "B" when asked for ``'b'``,
285 resource B's ``__getitem__`` is then asked for the name ``'c'``, and may
286 return resource "C".
c6e58bb - Add startup process docs.
Chris McDonough authored
287
288 #. Traversal ends when a) the entire path is exhausted or b) when any
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
289 resouce raises a :exc:`KeyError` from its ``__getitem__`` or c) when any
290 non-final path element traversal does not have a ``__getitem__`` method
83940c9 @Cito Some typos, better quoting in Traversal docs.
Cito authored
291 (resulting in a :exc:`AttributeError`) or d) when any path element is
292 prefixed with the set of characters ``@@`` (indicating that the characters
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
293 following the ``@@`` token should be treated as a :term:`view name`).
c6e58bb - Add startup process docs.
Chris McDonough authored
294
450006e @mcdonc wording
mcdonc authored
295 #. When traversal ends for any of the reasons in the previous step, the last
296 resource found during traversal is deemed to be the :term:`context`. If
297 the path has been exhausted when traversal ends, the :term:`view name` is
298 deemed to be the empty string (``''``). However, if the path was *not*
299 exhausted before traversal terminated, the first remaining path segment
300 is treated as the view name.
301
302 #. Any subsequent path elements after the :term:`view name` is found are
303 deemed the :term:`subpath`. The subpath is always a sequence of path
304 segments that come from ``PATH_INFO`` that are "left over" after
305 traversal has completed.
306
307 Once the :term:`context` resource, the :term:`view name`, and associated
308 attributes such as the :term:`subpath` are located, the job of
309 :term:`traversal` is finished. It passes back the information it obtained to
310 its caller, the :app:`Pyramid` :term:`Router`, which subsequently invokes
311 :term:`view lookup` with the context and view name information.
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
312
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
313 The traversal algorithm exposes two special cases:
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
314
450006e @mcdonc wording
mcdonc authored
315 - You will often end up with a :term:`view name` that is the empty string as
316 the result of a particular traversal. This indicates that the view lookup
317 machinery should look up the :term:`default view`. The default view is a
318 view that is registered with no name or a view which is registered with a
319 name that equals the empty string.
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
320
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
321 - If any path segment element begins with the special characters ``@@``
322 (think of them as goggles), the value of that segment minus the goggle
323 characters is considered the :term:`view name` immediately and traversal
324 stops there. This allows you to address views that may have the same names
325 as resource names in the tree unambiguously.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
326
450006e @mcdonc wording
mcdonc authored
327 Finally, traversal is responsible for locating a :term:`virtual root`. A
328 virtual root is used during "virtual hosting"; see the
329 :ref:`vhosting_chapter` chapter for information. We won't speak more about
330 it in this chapter.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
331
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
332 .. image:: resourcetreetraverser.png
125e974 Adjust for 7.5x9.25in output.
Chris McDonough authored
333
8c56ae4 - Added manual index entries to generated index.
Chris McDonough authored
334 .. index::
c5f24b2 Prep for b1
Chris McDonough authored
335 single: traversal examples
8c56ae4 - Added manual index entries to generated index.
Chris McDonough authored
336
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
337 Traversal Algorithm Examples
338 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
339
450006e @mcdonc wording
mcdonc authored
340 No one can be expected to understand the traversal algorithm by analogy and
341 description alone, so let's examine some traversal scenarios that use
342 concrete URLs and resource tree compositions.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
343
344 Let's pretend the user asks for
450006e @mcdonc wording
mcdonc authored
345 ``http://example.com/foo/bar/baz/biz/buz.txt``. The request's ``PATH_INFO``
346 in that case is ``/foo/bar/baz/biz/buz.txt``. Let's further pretend that
347 when this request comes in that we're traversing the following resource tree:
23bfce0 @blaflamme Narrative doc cleanup
blaflamme authored
348
349 .. code-block:: text
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
350
351 /--
352 |
353 |-- foo
354 |
355 ----bar
356
357 Here's what happens:
358
450006e @mcdonc wording
mcdonc authored
359 - :mod:`traversal` traverses the root, and attempts to find "foo", which it
360 finds.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
361
450006e @mcdonc wording
mcdonc authored
362 - :mod:`traversal` traverses "foo", and attempts to find "bar", which it
363 finds.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
364
7a2ab71 @cmbeelby First batch of fixes for typo's and other language issues.
cmbeelby authored
365 - :mod:`traversal` traverses "bar", and attempts to find "baz", which it does
450006e @mcdonc wording
mcdonc authored
366 not find (the "bar" resource raises a :exc:`KeyError` when asked for
367 "baz").
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
368
450006e @mcdonc wording
mcdonc authored
369 The fact that it does not find "baz" at this point does not signify an error
370 condition. It signifies that:
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
371
450006e @mcdonc wording
mcdonc authored
372 - the :term:`context` is the "bar" resource (the context is the last resource
373 found during traversal).
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
374
7bc20e1 General editing walkthrough.
Chris McDonough authored
375 - the :term:`view name` is ``baz``
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
376
7bc20e1 General editing walkthrough.
Chris McDonough authored
377 - the :term:`subpath` is ``('biz', 'buz.txt')``
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
378
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
379 At this point, traversal has ended, and :term:`view lookup` begins.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
380
780999e @mcdonc context finding -> resource location
mcdonc authored
381 Because it's the "context" resource, the view lookup machinery examines "bar"
382 to find out what "type" it is. Let's say it finds that the context is a
383 ``Bar`` type (because "bar" happens to be an instance of the class ``Bar``).
384 Using the :term:`view name` (``baz``) and the type, view lookup asks the
385 :term:`application registry` this question:
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
386
450006e @mcdonc wording
mcdonc authored
387 - Please find me a :term:`view callable` registered using a :term:`view
388 configuration` with the name "baz" that can be used for the class ``Bar``.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
389
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
390 Let's say that view lookup finds no matching view type. In this
450006e @mcdonc wording
mcdonc authored
391 circumstance, the :app:`Pyramid` :term:`router` returns the result of the
392 :term:`not found view` and the request ends.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
393
fb6a5ce @mcdonc model -> resource; resource -> asset
mcdonc authored
394 However, for this tree:
23bfce0 @blaflamme Narrative doc cleanup
blaflamme authored
395
396 .. code-block:: text
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
397
398 /--
399 |
400 |-- foo
401 |
402 ----bar
403 |
404 ----baz
405 |
406 biz
407
408 The user asks for ``http://example.com/foo/bar/baz/biz/buz.txt``
409
450006e @mcdonc wording
mcdonc authored
410 - :mod:`traversal` traverses "foo", and attempts to find "bar", which it
411 finds.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
412
450006e @mcdonc wording
mcdonc authored
413 - :mod:`traversal` traverses "bar", and attempts to find "baz", which it
414 finds.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
415
450006e @mcdonc wording
mcdonc authored
416 - :mod:`traversal` traverses "baz", and attempts to find "biz", which it
417 finds.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
418
450006e @mcdonc wording
mcdonc authored
419 - :mod:`traversal` traverses "biz", and attempts to find "buz.txt" which it
420 does not find.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
421
450006e @mcdonc wording
mcdonc authored
422 The fact that it does not find a resource related to "buz.txt" at this point
423 does not signify an error condition. It signifies that:
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
424
450006e @mcdonc wording
mcdonc authored
425 - the :term:`context` is the "biz" resource (the context is the last resource
426 found during traversal).
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
427
7bc20e1 General editing walkthrough.
Chris McDonough authored
428 - the :term:`view name` is "buz.txt"
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
429
7bc20e1 General editing walkthrough.
Chris McDonough authored
430 - the :term:`subpath` is an empty sequence ( ``()`` ).
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
431
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
432 At this point, traversal has ended, and :term:`view lookup` begins.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
433
450006e @mcdonc wording
mcdonc authored
434 Because it's the "context" resource, the view lookup machinery examines the
435 "biz" resource to find out what "type" it is. Let's say it finds that the
436 resource is a ``Biz`` type (because "biz" is an instance of the Python class
437 ``Biz``). Using the :term:`view name` (``buz.txt``) and the type, view
438 lookup asks the :term:`application registry` this question:
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
439
dae1d57 Roles.
Chris McDonough authored
440 - Please find me a :term:`view callable` registered with a :term:`view
441 configuration` with the name ``buz.txt`` that can be used for class
442 ``Biz``.
0bc787d More docs; fix autogen app model root creation.
Chris McDonough authored
443
450006e @mcdonc wording
mcdonc authored
444 Let's say that question is answered by the application registry; in such a
445 situation, the application registry returns a :term:`view callable`. The
446 view callable is then called with the current :term:`WebOb` :term:`request`
447 as the sole argument: ``request``; it is expected to return a response.
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
448
780999e @mcdonc context finding -> resource location
mcdonc authored
449 .. sidebar:: The Example View Callables Accept Only a Request; How Do I Access the Context Resource?
450
451 Most of the examples in this book assume that a view callable is typically
452 passed only a :term:`request` object. Sometimes your view callables need
453 access to the :term:`context` resource, especially when you use
454 :term:`traversal`. You might use a supported alternate view callable
455 argument list in your view callables such as the ``(context, request)``
456 calling convention described in
457 :ref:`request_and_context_view_definitions`. But you don't need to if you
458 don't want to. In view callables that accept only a request, the
459 :term:`context` resource found by traversal is available as the
460 ``context`` attribute of the request object, e.g. ``request.context``.
461 The :term:`view name` is available as the ``view_name`` attribute of the
462 request object, e.g. ``request.view_name``. Other :app:`Pyramid`
463 -specific request attributes are also available as described in
c5f24b2 Prep for b1
Chris McDonough authored
464 :ref:`special_request_attributes`.
590fe7c Massive overhaul to deal with the reality that we don't map URLs dire…
Chris McDonough authored
465
8cb6820 @mcdonc - Reordered chapters in narrative section for better new user friendl…
mcdonc authored
466 .. index::
467 single: resource interfaces
468
469 .. _using_resource_interfaces:
470
471 Using Resource Interfaces In View Configuration
472 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
473
474 Instead of registering your views with a ``context`` that names a Python
475 resource *class*, you can optionally register a view callable with a
476 ``context`` which is an :term:`interface`. An interface can be attached
477 arbitrarily to any resource object. View lookup treats context interfaces
478 specially, and therefore the identity of a resource can be divorced from that
479 of the class which implements it. As a result, associating a view with an
480 interface can provide more flexibility for sharing a single view between two
481 or more different implementations of a resource type. For example, if two
482 resource objects of different Python class types share the same interface,
483 you can use the same view configuration to specify both of them as a
484 ``context``.
485
486 In order to make use of interfaces in your application during view dispatch,
487 you must create an interface and mark up your resource classes or instances
488 with interface declarations that refer to this interface.
489
490 To attach an interface to a resource *class*, you define the interface and
1ca5b34 @mcdonc - Replace all mentions of zope.interface.implements with
mcdonc authored
491 use the :func:`zope.interface.implementer` class decorator to associate the
492 interface with the class.
8cb6820 @mcdonc - Reordered chapters in narrative section for better new user friendl…
mcdonc authored
493
494 .. code-block:: python
495 :linenos:
496
497 from zope.interface import Interface
1ca5b34 @mcdonc - Replace all mentions of zope.interface.implements with
mcdonc authored
498 from zope.interface import implementer
8cb6820 @mcdonc - Reordered chapters in narrative section for better new user friendl…
mcdonc authored
499
500 class IHello(Interface):
501 """ A marker interface """
502
1ca5b34 @mcdonc - Replace all mentions of zope.interface.implements with
mcdonc authored
503 @implementer(IHello)
8cb6820 @mcdonc - Reordered chapters in narrative section for better new user friendl…
mcdonc authored
504 class Hello(object):
1ca5b34 @mcdonc - Replace all mentions of zope.interface.implements with
mcdonc authored
505 pass
8cb6820 @mcdonc - Reordered chapters in narrative section for better new user friendl…
mcdonc authored
506
507 To attach an interface to a resource *instance*, you define the interface and
508 use the :func:`zope.interface.alsoProvides` function to associate the
509 interface with the instance. This function mutates the instance in such a
510 way that the interface is attached to it.
511
512 .. code-block:: python
513 :linenos:
514
515 from zope.interface import Interface
516 from zope.interface import alsoProvides
517
518 class IHello(Interface):
519 """ A marker interface """
520
521 class Hello(object):
522 pass
523
524 def make_hello():
525 hello = Hello()
526 alsoProvides(hello, IHello)
527 return hello
528
529 Regardless of how you associate an interface, with a resource instance, or a
530 resource class, the resulting code to associate that interface with a view
531 callable is the same. Assuming the above code that defines an ``IHello``
532 interface lives in the root of your application, and its module is named
533 "resources.py", the interface declaration below will associate the
534 ``mypackage.views.hello_world`` view with resources that implement, or
535 provide, this interface.
536
537 .. code-block:: python
538 :linenos:
539
540 # config is an instance of pyramid.config.Configurator
541
542 config.add_view('mypackage.views.hello_world', name='hello.html',
543 context='mypackage.resources.IHello')
544
545 Any time a resource that is determined to be the :term:`context` provides
546 this interface, and a view named ``hello.html`` is looked up against it as
547 per the URL, the ``mypackage.views.hello_world`` view callable will be
548 invoked.
549
550 Note, in cases where a view is registered against a resource class, and a
551 view is also registered against an interface that the resource class
552 implements, an ambiguity arises. Views registered for the resource class take
553 precedence over any views registered for any interface the resource class
554 implements. Thus, if one view configuration names a ``context`` of both the
555 class type of a resource, and another view configuration names a ``context``
556 of interface implemented by the resource's class, and both view
557 configurations are otherwise identical, the view registered for the context's
558 class will "win".
559
560 For more information about defining resources with interfaces for use within
561 view configuration, see :ref:`resources_which_implement_interfaces`.
562
563
590fe7c Massive overhaul to deal with the reality that we don't map URLs dire…
Chris McDonough authored
564 References
565 ----------
566
450006e @mcdonc wording
mcdonc authored
567 A tutorial showing how :term:`traversal` can be used within a :app:`Pyramid`
568 application exists in :ref:`bfg_wiki_tutorial`.
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
569
8a1b50b @caseman Split view chapter, move view config after templates, some reordering…
caseman authored
570 See the :ref:`view_config_chapter` chapter for detailed information about
41cc8f5 Traversal mini-overhaul.
Chris McDonough authored
571 :term:`view lookup`.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
572
450006e @mcdonc wording
mcdonc authored
573 The :mod:`pyramid.traversal` module contains API functions that deal with
574 traversal, such as traversal invocation from within application code.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
575
fb90f01 @mcdonc - The ``route_url``, ``route_path``, ``resource_url``, ``static_url``…
mcdonc authored
576 The :meth:`pyramid.request.Request.resource_url` method generates a URL when
577 given a resource retrieved from a resource tree.
223d4c0 More pass overhaul based on making contextfinding explicit within doc…
Chris McDonough authored
578
Something went wrong with that request. Please try again.