1

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.

3
  • 2
    May I suggest that you avoid CGI in the first place? Commented 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. Commented Jun 28, 2011 at 21:22
  • Yes, it is possible, but the way to do it depends on what web framework you are using. Commented Jun 28, 2011 at 22:38

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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!
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
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.

3 Comments

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.
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.
Mmm...I tried (with both POST and GET request), but it doesn't work, I don't get anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.