Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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.

James Cooke

May 07, 2013
Tweet

More Decks by James Cooke

Other Decks in Technology

Transcript

  1. 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.
  2. 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
  3. 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'}
  4. URL Dispatch summary • Simplest way to get started with

    Pyramid. • Covers most use cases. • Familiar to users experienced with other platforms.
  5. 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 @@.
  6. 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.
  7. 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.
  8. Traversal Caution • URL Encode & Decode implications. • Test

    your tree. • URL generation can be 'odd'. • Resource / view collision.
  9. 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.
  10. Traversal Summary • More flexibility that URL Dispatch. • Paid

    for with complexity. • Check the docs for 'corner cases'.
  11. 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