Building Data-Driven Web Apps with Pyramid and SQLAlchemy Transcripts
Chapter: Introducing the Pyramid framework
Lecture: Building block: Routes and URLs

Login or purchase this course to watch this video and the rest of the course contents.
0:00 The next major building block to cover is routing, or routing, if you prefer British English. Routes allow us to define patterns that match
0:09 some URL and map over to a particular view or controller method. Sometimes that just says, "This URL calls this function,"
0:19 other times it says, "This URL contains Data," so like /package/request or /package/sqlalchemy would pass the request or SQLAlchemy to that function.
0:32 So, let's see how we do this in Pyramid. So, we're going to go to the main method in the __init__.py file
0:37 that is basically the entry point or the start up for our web application, or we're going to start with this thing that's a configuration file reader.
0:46 On there, it has a function called add_static_view. So here, we're naming the route static, and saying it maps to /static or anything under there.
0:55 So, what we can do is we can go here and say anything in this directory or below it, will be cached by a quick little calculation.
1:04 It's one month, so you've got to put an integer that is the number of seconds to cache it for, I like to put this as calculation so I can see
1:11 60 seconds, 60 minutes, 24 hours a day, 31 days, okay, that's a month. Then we're going to define the routes that are the various URLs
1:20 that go to our action methods. So the first one is /, just like that, and that's home. Right, that's just the basically the main page
1:30 when you hit the site. And we want to have a /help so add a route for that for help. Then we're going to have, in our PyPI example,
1:39 the route that they use for an individual package or the URL is /project/{package_name}. Now notice, this one is different.
1:47 It has package_name as a curly bracket and then a variable looking thing. package_name will actually be passed to the function that we apply this to.
1:58 So, like I explained before, SQLAlchemy, requests, whatever so the URL itself will carry the information along and that's defined in the route here.
2:09 Also, we have things like account/login. And the final action to do is to tell the system to go figure out what functions are associated with these,
2:18 so we have the route name, we also need to have to have the route to actually apply to this. So we run the scans and it looks through all
2:26 the Python files, looks for that view_config decorator using various route names and then it puts those two things together.
2:35 And finally, we have to return this WSGI application, W-S-G-I, WSGI, application that the web framework's going to use and this is just at the end
2:44 of the main startup always. So this is how you define routes in pyramid.


Talk Python's Mastodon Michael Kennedy's Mastodon