Adding a CMS to Your Pyramid Web App Transcripts
Chapter: Redirects and the admin section
Lecture: Concept: Viewmodels

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Now, before we move on, let's take our code that we've written and make it better
0:05 make it easier to test and make all the different parts that we work with more focused
0:10 And we're gonna do that following this thing called a 'view model pattern'
0:15 Now the website, the data driven website, has been using view models all over the place because that was how it was built
0:21 But we just started from there and we had it on the CMS thing So you might not have noticed this idea of a view model So what is this?
0:28 Well, it's most useful when you're accepting user input You have an HTML form. People are filling it out. They hit, save. It goes back to the website.
0:36 That data has to be synchronized back to Python. You know, what do they type into the form? Are all the required fields there?
0:43 Maybe there's conversions. They typed in a string. You got to convert it to a number or a date or something like that. So the idea of the view model is
0:50 we're going to take what would otherwise be a really complicated and long method here. This is like our CMS requests that we were just messing with,
0:59 and as we add more validation as we add more logic, this just gets longer and longer and it's more complicated and it's harder to test.
1:08 So what we're gonna do is we're gonna break it into two things. The view method that actually handles the requests that works with the Web Framework.
1:15 Works with pyramid, returns the responses. And then this thing we're calling the view model. This is what we're gonna build.
1:21 This is a separate Python class that knows what data should be exchanged, what is valid, what is invalid. What is the logic to do all that stuff.
1:29 So instead of having that long, view method all in one, we're gonna have a view model That it's created by the view method.
1:36 It gets all the data and validates everything and then it comes back and just helps the view method do its magic.
1:42 Also, this is gonna help with testing if we want to write tests because it's easy to test the view model outside of the Web framework.
1:49 It typically doesn't need much in terms of what's going on there, Whereas maybe the view method is much more complicated.
1:56 Gotta start up the website, the Web app, and get it all up and running before it can actually do its thing


Talk Python's Mastodon Michael Kennedy's Mastodon