#100DaysOfWeb in Python Transcripts
Chapter: Days 81-84: Unit testing web apps
Lecture: Concept: View models

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Before we go on to testing. Let's quickly review this concept of a ViewModel. So this is a pattern that I borrowed from other places
0:08 but I think makes a lot of sense on web applications. The idea is, typically, this is most useful when you have forms and some user data
0:15 but it also works when there's just straight GETs. So in this case we have a HTML form and it's going to submit some data
0:21 to register the user on the site. Traditionally the way web applications might be written is there's one huge, long view
0:29 or action method that has to do all the work. And it's all crammed in there, all the validation all the data exchange, everything.
0:35 And that makes it hard to see what's actually happening. And actually test that separately from all the things going on around it
0:42 instead what we're going to do is we're going to exchange this one huge method doing all the stuff with a couple of pieces
0:47 of code that do more single responsibility-style programing. One core thing. So let's change this up a little bit.
0:55 Make a smaller viewer action method in the ViewModel that does this data exchange invalidation. And then the action method
1:02 is just going to work with the ViewModel. So where's the value? Well you'll see that our code we write
1:07 in this case the register method, is much simpler. The GET one is incredibly simple. So we just call this two dictionary and in the POST we'll create
1:15 our registration ViewModel's case. Do some validation from the form. Check to see whether there's an error.
1:22 The data that gets exchanged, it's always consistent. Cause this to_dict always returns the same thing that can cause an error if you omit a key
1:28 from a dictionary, for example. And then we can just check. Just do the simple code we're suppose to do. Are they registered? Yes or no. Did that work?
1:37 Yes or no. If it didn't we're going to need to set an error and return that. Otherwise we just take them on to where they were going.
1:42 Alright take them to the homepage. Great, you're logged in now. So as you can see this would be much more complicated with lots
1:47 of reading and converting values out of dictionaries and checking that they exist and things like that. But all of that has been moved
1:54 over to this registration ViewModel. It's beautiful.


Talk Python's Mastodon Michael Kennedy's Mastodon