raw post data

Bengt Richter bokr at oz.net
Tue Sep 17 20:56:50 CEST 2002


On Tue, 17 Sep 2002 06:52:08 GMT, Alex Martelli <aleax at aleax.it> wrote:

>:B nerdy wrote:
>
>> how could i make it so when i read the stdin it still is there.. cause i
>> use cgi.FormVariables() also
>
>When you instantiate class cgi.FieldStorage (there's no such
>thing as cgi.FormVariables, so I'm just guessing at what it IS
>that you want!) you can pass it an optional first parameter
>that is a file object open for reading -- it uses sys.stdin
>as the default if you don't pass the first parameter.
>
>Thus, the following should work (untested!):
>
>import cgi, sys, cStringIO
>
>copyInput = cStringIO.StringIO(sys.stdin.read())
>fieldStorage = cgi.FieldStorage(copyInput)
>
>
>The raw posted data are now available as the string returned
>by calling copyInput.getvalue(), and are also parsed by cgi to
>obtain fieldStorage.
>
A nit, but it might be good to check that the environment
variable REQUEST_METHOD exists and == 'POST',
and to attempt to read not more than the most you expect to be able to handle,
and to check that what you get with your max read is what it's supposed to be,
e.g., (untested!) (you specify MAX_I_HANDLE) (inside appropriate try/except)

    import os
    ...
    if os.environ.get('REQUEST_METHOD') is None or os.environ.get('REQUEST_METHOD') != 'POST':
        raise ValueError, 'Request method not POST'
    if os.environ.get('CONTENT_LENGTH') is None: raise ValueError, 'Content length unspecified'
    content_length = int(os.environ.get('CONTENT_LENGTH'))
    if content_length == 0: raise ValueError, 'Content length zero'
    elif content_length > MAX_I_HANDLE: raise valueError, 'Content length too great: %s' % content_length 
    copyInput = cStringIO.StringIO(sys.stdin.read(MAX_I_HANDLE))
    if len(copyInput) != content_length:
        raise IOError, 'Data bytes read (%s) not == CONTENT_LENGTH (%s)' % (len(copyInput), content_length)
    ...

Regards,
Bengt Richter



More information about the Python-list mailing list