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.
精彩评论