Python CGI helper function – Convert POST to GET
Why do this?
I made a small Python-based website that outputs results based on user supplied data from a form. The form is submitted using POST but I wanted to let people bookmark or link to their results which requires creating a link which includes all of the data that generated their page.
Here’s how I did it:
Instead of converting the whole site to use GET, I wrote this conversion function that works with Python’s cgi module:
This is the function:
#do these imports somewhere in your module of course.
import cgi
import urllib
def convertpost_to_get(baseurl,postdata):
"""Convert POST data into get data and return the Get url.
This is useful for creating a "link to this page" or "bookmark this page"
type of link for your post results.
"""
if not postdata.keys():
return baseurl
query_items=[(key,postdata.getfirst(key)) for key in postdata.keys()]
baseurl+='?'+urllib.urlencode(query_items,0)
return baseurl
This is how you would use it:
import cgi
form = cgi.FieldStorage()
url_linkback=convertpost_to_get(
baseurl=r"http://www.yourURL.com/index.py",postdata=form)
print '<a href="%s">Link to this page!</a>' % url_linkback
This all works by taking advantage of the fact that Python’s cgi module doesn’t make a distinction between data passed via GET or via POST (At least for this purpose). So that means when you script gets this link you made, it will behave the same way it does for post data. Well at least it does for me. If you have more complex POST data then your results may vary and you could have to do some tweaking. Definitely let me know what you did and I’ll update this post.
Disclaimer:
I’m fairly new to Python CGI programming, hence I have no idea what I’m doing, but this does work for me. Caveat emptor
Update:
I modified this to encode the url parameters with urllib.urlencode. It will now work even if you have amperstands and such in your data.
[tags]Python CGI, GET, POST, HTTP GET,HTTP POST[/tags]