Is there a way to accept parameters only from POST request? If I use cgi.FieldStorage() from cgi module, it accepts parameters from both GET and POST request.
Asked
Active
Viewed 917 times
1
-
2May I suggest that you avoid CGI in the first place? – Ignacio Vazquez-Abrams Jun 28 '11 at 21:19
-
Do you mean python cgi module? If yes, no problem to avoid it. I just want a way to do what I asked. – stdio Jun 28 '11 at 21:22
-
Yes, it is possible, but the way to do it depends on what web framework you are using. – ʇsәɹoɈ Jun 28 '11 at 22:38
2 Answers
2
By default, most things in the cgi
module merge os.environ['QUERY_STRING']
and sys.stdin
(in the format suggested by os.environ['CONTENT_TYPE']
). So the simple solution would be to modify os.environ
, or rather, provide an alternative, with no query string.
# make a COPY of the environment
environ = dict(os.environ)
# remove the query string from it
del environ['QUERY_STRING']
# parse the environment
form = cgi.FieldStorage(environ=environ)
# form contains no arguments from the query string!
Ignacio Vazquez-Abrams suggests avoiding the cgi
module altogether; modern python web apps should usually adhere to the WSGI interface. That might instead look like:
import webob
def application(environ, start_response):
req = webob.Request(environ)
if req.method == 'POST':
# do something with req.POST
# still a CGI application:
if __name__ == '__main__':
import wsgiref.handlers
wsgiref.handlers.CGIHandler().run(application)

SingleNegationElimination
- 151,563
- 33
- 264
- 304
-
Perfect! They are both good ways, but I prefer don't use external modules in this case, so I'll use the first way. Thanks a lot! – stdio Jun 28 '11 at 23:37
-
That's unfortunate. An amazing amount of work is totally boilerplate when dealing with web-apps. `webob` is about the thinnest veneer of a no-framework framework around for wsgi (it's even less magical than `cgi` but is generally more useful). You really should build your app on top of a solid framework and focus on the actual *problem you're trying to solve* – SingleNegationElimination Jun 29 '11 at 00:40
0
From the documentation, I think you can do the following:
form = cgi.FieldStorage()
if isinstance(form["key"], cgi.FieldStorage):
pass #handle field
This code is untested.

Jasmijn
- 9,370
- 2
- 29
- 43
-
This seems a way to reject "key" parameter and I don't want this. I want to accept a parameter only from POST request and not GET. – stdio Jun 28 '11 at 21:38
-
This is supposed to to only handle POST requests. URL parameters in GET requests use `cgi.MiniFieldStorage`. It might not be fail safe (for example, for when you come across a POST request with URL parameters), but it's a quick fix. – Jasmijn Jun 28 '11 at 21:45
-
Mmm...I tried (with both POST and GET request), but it doesn't work, I don't get anything. – stdio Jun 28 '11 at 21:58