Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Introducing the Flask framework
Lecture: Building block: Models
0:00 Here's another view method.
0:01 It's going to return the popular packages.
0:03 This is going to be the most popular packages on PyPI
0:07 and we're going to have the name and the summary for each one
0:10 and the URL for each one, and we'll have a list of those.
0:13 And our template, popular.html, is going to need that list
0:17 with all those details to generate dynamically some kind
0:20 of unordered list or whatever it is.
0:22 So what we're going to do is
0:23 we're going to come up with this data.
0:25 Here, we're just kind of hacking it in.
0:26 But in reality, popular would probably be a query
0:30 from the database with an order by
0:32 number of downloads this month
0:33 or something kind of complicated like that.
0:36 So we'll somehow, usually database or other API
0:38 we're going to get the most popular packages
0:41 and we need to provide that to the template.
0:44 So here, we say render template, give the template name
0:46 and then we have keyword arguments
0:49 packages and then our list here.
0:50 So in the template, it's going to be a variable
0:53 to find packages, and it's going to have this value here.
0:56 And we can pass as many of these as we want
0:59 or could even have a dictionary unpack it
1:01 or like I said at the beginning of this chapter
1:03 there's actually some cool patterns
1:04 where we would just return a dictionary itself.
1:07 So this is the model that flows
1:09 from the view methods over to the template.
1:12 So here, we're going to pass these by keyword arguments
1:15 and we can also pass methods or functions.
1:19 That's pretty cool, because sometimes you want
1:21 to have a little helper function that convert this
1:23 to an integer or give me a default value
1:25 or get the name of this, unless it's not there
1:28 then just return none, or something to this effect.
1:31 There's some cool little helper functions
1:32 that we might want to pass along
1:34 and if they're in this code or we have access to them
1:36 in this code, we could actually say
1:38 helper function a equals just the name of the function
1:41 and that's also available to our template.
1:44 This could be data or behavior
1:46 we need to pass along to our view.