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.
-
2May I suggest that you avoid CGI in the first place?Ignacio Vazquez-Abrams– Ignacio Vazquez-Abrams2011-06-28 21:19:41 +00:00Commented Jun 28, 2011 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– stdio2011-06-28 21:22:25 +00:00Commented Jun 28, 2011 at 21:22
-
Yes, it is possible, but the way to do it depends on what web framework you are using.ʇsәɹoɈ– ʇsәɹoɈ2011-06-28 22:38:00 +00:00Commented Jun 28, 2011 at 22:38
Add a comment
|
2 Answers
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)
2 Comments
stdio
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!
SingleNegationElimination
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 solveFrom 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.
3 Comments
stdio
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.
Jasmijn
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.stdio
Mmm...I tried (with both POST and GET request), but it doesn't work, I don't get anything.