开发者

Accept parameters only from POST request in python

开发者 https://www.devze.com 2023-03-16 04:55 出处:网络
Is there a way to accept parameter开发者_如何学运维s only from POST request? If I use cgi.FieldStorage() from cgi module, it accepts parameters from both GET and POST request.By default, most things i

Is there a way to accept parameter开发者_如何学运维s only from POST request? If I use cgi.FieldStorage() from cgi module, it accepts parameters from both GET and POST request.


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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消