Chapter: Surveying the non-js-enabled Flask app
Lecture: Concept: Pydantic models
0:00 Here's our first concept video, and before we get to the content on the screen,
0:03 let me just do a quick sidebar.
0:05 When we're going through these demos,
0:06 you're seeing everything built up hands on, and sometimes it takes five or six minutes to
0:11 figure out. You know, here's how we build up this idea.
0:14 But there's little takeaways that will help you now,
0:17 but will really help you if you try to use this course as reference material,
0:20 like, oh, what was that thing we did with Pydantic models? or how did
0:24 you query that data? or whatever.
0:27 That's what the idea of these concept videos are about.
0:30 It's here to remind you and refresh your memory.
0:33 For example, here about Pydantic models,
0:35 but you just saw them. It's more here for reference material, so you can go
0:39 and watch a one-minute, two-minute video and get the core idea of a concept
0:44 and run with it. With that mind,
0:46 let's talk about a few concepts. Pydantic models,
0:48 these models are very similar to data classes,
0:51 but they're a little more web friendly.
0:53 They'll take data that's not exactly in the right format and structure, and they'll,
0:57 if possible, convert it and parse it into that structure, and they'll otherwise give you really
1:02 good validation error messages. I'm a big fan of Pydantic as a way to describe our data.
1:08 Here, we're creating a category class.
1:09 And in order to make it a Pydantic model,
1:11 you simply derive from base model which comes from pydantic.
1:15 Then you say all the fields colon the type.
1:18 So here's a category. It's a string in this case we're telling Pydantic it has
1:22 to have a string. It can't possibly be omitted from the data,
1:25 for example. If it was not necessarily required,
1:29 but could be there, you would say it's an optional string.
1:31 So the python type hints,
1:33 or type annotations are super important
1:35 here. We have an image which is also required because it's a non optional string.
1:40 And we have a list of videos,
1:41 which is a set of other Pydantic models.
1:44 We saw the video classes, also a Pydantic model,
1:47 so they can be nested in this way.
1:49 And what we do is we just go to that JSON file and say for each
1:53 category in the JSON list, give it to Pydantic and let it turn it into
1:56 this class. A really nice way to create structured, verified, typed data in Python.