Hello Traversal World

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:

 1from wsgiref.simple_server import make_server
 2from pyramid.config import Configurator
 3from pyramid.response import Response
 4
 5
 6class Resource(dict):
 7    pass
 8
 9
10def get_root(request):
11    return Resource({'a': Resource({'b': Resource({'c': Resource()})})})
12
13
14def hello_world_of_resources(context, request):
15    output = "Here's a resource and its children: %s" % context
16    return Response(output)
17
18
19if __name__ == '__main__':
20    with Configurator() as config:
21        config.set_root_factory(get_root)
22        config.add_view(hello_world_of_resources, context=Resource)
23        app = config.make_wsgi_app()
24    server = make_server('0.0.0.0', 6543, app)
25    server.serve_forever()

You may notice that this application is intentionally very similar to the "hello world" application from Creating Your First Pyramid Application.

On lines 6-7, we create a trivial resource class that's just a dictionary subclass.

On lines 10-11, we hard-code a resource tree in our root factory function.

On lines 14-15, we define a single 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 Pyramid WSGI app. Line 22 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:6543, and the user browses to http://localhost:6543/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:6543/, 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:6543/xyz or http://localhost:6543/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.

参考

Full technical details may be found in Traversal.

For more about why you might use traversal, see Much Ado About Traversal.