Search code examples
form-submitpost-redirect-get

How do I implement Post-redirect-get on Google App Engine with Python?


I am developing an online bidding system on Google App Engine with Python. Regarding the post-redirect-get mechanism, I've been googling a while and still have no clear idea of how to implement it. Suppose:

HTML:

<form action="/test" method="post">
  ...
  <input type="submit" value="Submit" />
</form>

Python:

# Collect data from the posted form
...
# Save data into datastore
...
# Prepare template values

tempalteValues = { ... }
path = os.path.join(os.path.dirname(__file__), 'templates/', 'responseMessage.html')
handler.response.out.write(template.render(path, templateValues))

# Then what?

I have two questions:

1) After rendering the response message file, what should I do next? That is, how to implement the 'GET'?

2) Another strategy I can think of is: If the post is supposed to happen only once (e.g., product purchasing with a unique order number), can I set a flag in the entity indicating that the form has been submitted and the following posts will be ignored if the flag is set? Is this feasible or even correct?

(Note: because the order number is generated by the system, the entity has to be saved before the form submission in order to get that number)

Thanks in advance.


Solution

  • What you are looking for is building a Restful service something like this:

    class BiddingHandler(webapp2.RequestHandler):
        def get(self):
            #Get code goes here for this handler
    
        def post(self):
            #code that gets your posted data and processes it
    
        def delete(self):
            #code to delete something
    
    app = webapp2.WSGIApplication([('/bidding', BiddingHandler)])
    

    Looking at the above if you wanted to do a redirect after making a post in the last line of your post instead of rendering a template you would simply redirect the user to the get part of the handler with the following line:

    self.response.redirect('/bidding')
    

    What I have shown you above is the correct way to implement it. Writing to the datastore and reading from it for every request would mean more overhead and costs.