Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Course conclusion
Lecture: viewmodels
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
When we were accepting user input
0:01
we saw that there's a lot of validation
0:04
a lot of data exchange
0:05
and other things we have to do.
0:06
And that's not so much fun.
0:08
And the exact data and the format
0:11
of the data that we want to pass back and forth
0:12
also takes a lot of work.
0:14
So we decided to apply this design pattern
0:17
called view models.
0:18
And the idea is the view models
0:20
are tightly tied to the HTML form that
0:23
they're exchanging data with.
0:24
They know how to get the data
0:25
from the form and provide it back to it
0:28
or things like drop downs and where it needs it
0:30
and roundtrip it and so on.
0:31
It also knows how to do all the validation.
0:33
And that can be basic validation like
0:35
Hey, we require that you type in an email
0:37
address here, or, This has to be a number,
0:39
or, It has to bigger than five, and so on.
0:41
But it can also be richer, deeper validation like
0:44
Sorry, you can't register here.
0:46
You can't create an account with that email
0:48
'cause that email address is already
0:50
tied to another user.
0:51
Maybe you should just try to login
0:52
and reset your password.
0:54
And it's both made testing easier
0:56
'cause we can test the view models directly
0:59
and just do validation there.
1:00
Don't have to involve Flask
1:02
and HTTP infrastructure, and so on.
1:04
It also made our action methods
1:05
and our view methods much simpler, right?
1:08
They don't get larger and more complex
1:11
as we add more validation.
1:12
Just the one place where validation goes
1:14
the view models, does. But that's okay.
1:16
That's its job. Strongly recommend this pattern.
1:19
There's some other add-on libraries
1:21
for Flask and stuff that you can use for forms and whatnot.
1:23
But I really like this pattern
1:24
because you have complete control over it
1:26
and it's super straightforward and good for testing.