HTMX + Flask: Modern Python Web Apps, Hold the JavaScript Transcripts
Chapter: Surveying the non-js-enabled Flask app
Lecture: Concept: Pydantic models

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Here's our first concept video, and before we get to the content on the screen, let me just do a quick sidebar. When we're going through these demos,
0:07 you're seeing everything built up hands on, and sometimes it takes five or six minutes to figure out. You know, here's how we build up this idea.
0:15 But there's little takeaways that will help you now, but will really help you if you try to use this course as reference material,
0:21 like, oh, what was that thing we did with Pydantic models? or how did you query that data? or whatever.
0:28 That's what the idea of these concept videos are about. It's here to remind you and refresh your memory. For example, here about Pydantic models,
0:36 but you just saw them. It's more here for reference material, so you can go and watch a one-minute, two-minute video and get the core idea of a concept
0:45 and run with it. With that mind, let's talk about a few concepts. Pydantic models, these models are very similar to data classes,
0:52 but they're a little more web friendly. They'll take data that's not exactly in the right format and structure, and they'll,
0:58 if possible, convert it and parse it into that structure, and they'll otherwise give you really
1:03 good validation error messages. I'm a big fan of Pydantic as a way to describe our data. Here, we're creating a category class.
1:10 And in order to make it a Pydantic model, you simply derive from base model which comes from pydantic. Then you say all the fields colon the type.
1:19 So here's a category. It's a string in this case we're telling Pydantic it has to have a string. It can't possibly be omitted from the data,
1:26 for example. If it was not necessarily required, but could be there, you would say it's an optional string. So the Python type hints,
1:34 or type annotations are super important here. We have an image which is also required because it's a non optional string. And we have a list of videos,
1:42 which is a set of other Pydantic models. We saw the video classes, also a Pydantic model, so they can be nested in this way.
1:50 And what we do is we just go to that JSON file and say for each category in the JSON list, give it to Pydantic and let it turn it into
1:57 this class. A really nice way to create structured, verified, typed data in Python.

Talk Python's Mastodon Michael Kennedy's Mastodon