Dick Wong
Dick Wong

Reputation: 143

Python and CGI: Prevent resending form data upon refreshing

I am new to Python (somehow I started looking at python 2 days ago).

I tried to write a simple interactive webpage with CGI, and I used HTML form to get user input. However, as everyone knows, if I refresh the webpage, the form data will be resubmitted again. I just have no idea how to prevent this from happening.

The same problem, but in php/javascript, has been discussed and solutions can be found, but I would like to find the answer to the python case.

I hope there is someone here who can address my problem. Since I am not quite familiar with the language, I hope that, instead of solely giving me a descriptive solution, the kind one can also give me the pieces of codes necessary.

Thank you very much

Upvotes: 2

Views: 1299

Answers (3)

Helgi
Helgi

Reputation: 5436

Your question is not Python-specific, it's about the general web application design patterns.

  1. Use GETs for requests that do not change the web app's state (viewing, queries and so on). Render the page in the response.
  2. Use POST for whatever request that modifies the state (post submitting, editing, deleting).
  3. Never render anything in the response, provide a 303 See Other redirection to the page where the results of the POST can be seen. E.g., if the user added a comment on the page http://example.com/blog/123, the POST handler can be http://example.com/submitcomment, but it should return nothing but a redirection to http://example.com/blog/123#comment5.

That's what @mikep referred to as Post-Redirect-Get.

On the related note: do yourself a favor, skip CGI. There is a number of nice and clean web frameworks for Python. Try Flask or Bottle (smaller frameworks) or go straight to Django if you are building a big app. Search here on Stack Overflow for pros and cons of different frameworks.

Just skip CGI. It's hard to build a good and maintainable CGI app, there are too many things to take care of, things that are already thought if in the frameworks.

I've been wasting time supporting a CGI application for some time, and switching to a framework was a relief.

Upvotes: 3

mikep
mikep

Reputation: 21

Take a look at POST-REDIRECT-GET web programming patern.

Upvotes: 2

chochim
chochim

Reputation: 1740

You might want to view these lectures: http://www.udacity.com/overview/Course/cs253/CourseRev/apr2012

Week 2 will address your queries.

Upvotes: 2

Related Questions