Building Data-Driven Web Apps with Pyramid and SQLAlchemy Transcripts
Chapter: User input and HTML forms
Lecture: Concept: GET-POST-Redirect pattern
0:00 We went through several cycles of creating these GET and then POST view or action methods while building out our user interaction in the site.
0:11 So let's review some of those core concepts. Whenever we're going to start we typically start with a GET action. Because we're going to have to
0:19 show the form to the user before they can submit it, right? If this was like a RESTful API maybe that's not the case
0:25 but this is a website so we've got to show the data, the form and any initial data to the user so they can submit it back. So how's that work?
0:34 Well, we're going to set the GET request method and we're also going to set the route name to a shared URL. Right, so this is register.
0:43 It's going to be registered for GET and it's going to be registered for POST. Same thing with the template.
0:49 Then we need to make sure we have a unique function name. I like to just call it, register_get, _post, whatever.
0:58 It doesn't have to be named that way, but it must have a unique name that's not the same as POST or the other verbs or it's going to erase it. Right?
1:05 Python doesn't give you an error when you do that. It just takes the last one you typed in. And finally, we're going to pass any data the form needs
1:13 Really it's going to exchange. So we're going to pass the email address, the password, and even whether or not
1:19 there's an error. These are typically empty but if you have things like comboboxes and dropdowns and things like that, radio buttons, you might
1:25 pass those along to initially populate the form. So this is the GET action, this shows the form to the user.
1:32 They do some editing, then they are going to submit it back. In that case it's going to hit the POST action.
1:38 So again, we're going to set the verb, this time to POST and we're going to use this shared route name.
1:45 Again here's register for both the template or the render and the route name. We have our unique function name this time registe_post.
1:54 We have our data in this Post dictionary so we pull it out and we use the get instead of key access. That's a little bit safer.
2:02 This is just get it and check to see whether it was passed and we're going to do some validation, this is super important.
2:08 If it doesn't work pass that data back with some kind of error message. If it does you're going to do whatever processing you do here
2:16 and then probably redirect them. This is the final part of the get post redirect pattern.