Posting to a CGI script
August 14, 2002 | Fredrik Lundh
Q. I’m looking for a general way to have a CGI script fetch the whole body of an HTTP POST request and put in a variable.
When the CGI script runs, things are set up so that you can simply read from standard input.
variable = sys.stdin.read()
To avoid denial-of-service attacks, it’s probably a good idea to limit the amount of data read by the script:
bytes = int(os.environ.get("CONTENT_LENGTH", 0)) if bytes > MAX_REQUEST_SIZE: giveup("request too large") variable = sys.stdin.read(bytes)
variable = sys.stdin.read(MAX_REQUEST_SIZE) if len(variable) == MAX_REQUEST_SIZE and sys.stdin.read(1): giveup("request too large")
For a larger example, see Providing XML-RPC Services via CGI.