Building data-driven web apps with Pyramid and SQLAlchemy Transcripts
Chapter: User input and HTML forms
Lecture: GET-POST-Redirect pattern
0:00 Now before we write some code
0:01 let's talk a little bit about the flow
0:03 that people go through when they're working with forms.
0:05 There's many ways to do this
0:07 but there's one pattern that really helps
0:09 both organize your server side code
0:11 and prevent that annoying warning like
0:14 "are you sure you want to refresh this page?
0:17 "You've posted it, it might resubmit
0:19 "your purchase request" or whatever.
0:22 I'm calling this the Get Post Redirect pattern.
0:26 So what's that look like?
0:27 Well, we have of course our server.
0:30 Our server has some sort of data.
0:31 We have a web browser, and our web browser
0:33 is going to interact with our site.
0:35 It's going to say, "Hey, I want to view this HTML page
0:37 "that happens to have a form
0:38 "like I want to register for your site."
0:41 And then over here locally, they're like
0:42 "All right, great.
0:43 "Here's my username, here's my password, my name,"
0:47 whatever you got to do to register.
0:49 They type that in and they click that submit button
0:52 we just talked about.
0:53 That posts all that data back
0:55 and they're like, "Great, we've got a new account.
0:56 "We want to create it, we're going to save that to the database."
0:58 Now we're going to tell the browser to move over
1:02 to another page, redirect, send a temporary redirect
1:06 302 over to /welcome, and welcome to the site.
1:10 That way, if they bookmark it
1:12 or they refresh it or whatever
1:14 they're going to end up on welcome
1:16 having already created it not being left on the same URL
1:21 where a POST just happened.
1:22 Like I said, if you refreshed that
1:24 you would get a warning saying
1:26 "Hey, this page is going to resubmit
1:27 "Are you sure you want to do that?"
1:29 So this Get Post Redirect pattern is super common
1:32 and it's really nice on the server side.
1:35 I'll show you how to break that out
1:36 into different methods nice and easy
1:38 so one handles the get, one handles the post.
1:42 So one handles the show the form
1:45 pre-populated with starter data.
1:46 The other processes that input
1:48 and keeps the code really clean.
1:49 You don't have to test whether it's being submitted or not.
1:52 This common pattern is sometimes known
1:54 under a different name, the Post Redirect Get pattern.
1:59 So over here on Wikipedia, they have an article on it.
2:02 You can read more about it as you want.
2:04 To me, you have to start from somewhere
2:06 and you start from the get, and then you do the post
2:10 and then you do the redirect.
2:11 That's the life cycle of that form interaction.
2:14 So I think that's why I call it Get Post Redirect
2:16 but Wikipedia, they have a different name.
2:19 It's fine. It's a pretty common pattern
2:21 and you can get more information about it here.