Routing, Traversal and URL Dispatch with Pyramid

Routing, Traversal and URL Dispatch with Pyramid

Talk at Pyramid London, May 7th 2013 looking at the basics of routing with Pyramid.

B3c6f332ab773b78f4ebd72d56d7b6df?s=128

James Cooke

May 07, 2013
Tweet

Transcript

  1. Routing, Traversal & URL Dispatch Pyramid London // James Cooke

  2. The Pyramid Router • Created when you start a Pyramid

    app. • From the glossary: The router intercepts requests, invokes traversal and/or URL dispatch, calls view functions, and returns responses to the WSGI server on behalf of your Pyramid application.
  3. PyramidPress Example • Home page - Show a list of

    our users. • User view - web visitor looks at a member's blog. e.g. for Bob, his page is: /bob • Post view - web visitor looks at a member's single post. e.g. for Bob's motorbike page: /bob/motorbikes
  4. URL Dispatch mode Matches route patterns returns a matchdict. •

    User view route ◦ Route pattern = '/{username}' ◦ Matches '/bob' ◦ Returns {'username': u'bob'} • Page view route ◦ Route pattern = '/{username}/{page_title}' ◦ Matches '/bob/motors' ◦ Returns {'username':u'bob', 'page_title': u'motors'}
  5. URL Dispatch summary • Simplest way to get started with

    Pyramid. • Covers most use cases. • Familiar to users experienced with other platforms.
  6. Traversal Algorithm • Resources of two types: ◦ Container -

    dictionary-like, has __getitem__. ◦ Leaf. • Walk the URL until: ◦ Path is exhausted. ◦ KeyError is raised. ◦ Non-final element has no __getitem__. ◦ Path element starts with @@.
  7. Traversal Example • With '/' • Pyramid Router makes []

    • Returns root_resource. • Path exhausted. • Returns Root in response['context'] • View lookup now finds suitable view for Root context and calls it.
  8. Traversal Example • With '/bob/motors' • Pyramid Router makes [u'bob',

    u'motors'] • Calls root_resource.__getitem__(u'bob') ◦ Which returns <User name='bob'> • Calls bob.__getitem__(u'motors') ◦ Which returns <Page title=u'Motors'> • Path exhausted. • Returns Motors page in response['context'] • View lookup again goes to work.
  9. Traversal Caution • URL Encode & Decode implications. • Test

    your tree. • URL generation can be 'odd'. • Resource / view collision.
  10. Hybrid Applications • Play with Traversal in a safe way.

    • Routes like: config.add_route('user', '/user/*traverse') config.add_route('user_page', '/user/{page}/*traverse') • More URL Dispatch than Traversal.
  11. Traversal Summary • More flexibility that URL Dispatch. • Paid

    for with complexity. • Check the docs for 'corner cases'.
  12. Thanks for listening All code is on GitHub: github.com/jamescooke/pyramid-london-talk Find

    me on Twitter: @jamesfublo Ask me questions? I'll do my best to answer :D