Slide 1

Slide 1 text

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

Slide 2

Slide 2 text

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.

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

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'}

Slide 5

Slide 5 text

URL Dispatch summary ● Simplest way to get started with Pyramid. ● Covers most use cases. ● Familiar to users experienced with other platforms.

Slide 6

Slide 6 text

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 @@.

Slide 7

Slide 7 text

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.

Slide 8

Slide 8 text

Traversal Example ● With '/bob/motors' ● Pyramid Router makes [u'bob', u'motors'] ● Calls root_resource.__getitem__(u'bob') ○ Which returns ● Calls bob.__getitem__(u'motors') ○ Which returns ● Path exhausted. ● Returns Motors page in response['context'] ● View lookup again goes to work.

Slide 9

Slide 9 text

Traversal Caution ● URL Encode & Decode implications. ● Test your tree. ● URL generation can be 'odd'. ● Resource / view collision.

Slide 10

Slide 10 text

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.

Slide 11

Slide 11 text

Traversal Summary ● More flexibility that URL Dispatch. ● Paid for with complexity. ● Check the docs for 'corner cases'.

Slide 12

Slide 12 text

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