views:

407

answers:

1

I'm using WSGI and trying to access the get/post data, using this code:

import os
import cgi
from traceback import format_exception
from sys import exc_info

def application(environ, start_response):

    try:
        f = cgi.FieldStorage(fp=os.environ['wsgi.input'], environ=os.environ)
        output = 'Test: %s' % f['test'].value
    except:
        output = ''.join(format_exception(*exc_info()))

    status = '200 OK'
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

However I get the following error:

Traceback (most recent call last):
  File "/srv/www/vm/custom/gettest.wsgi", line 9, in application
    f = cgi.FieldStorage(fp=os.environ['wsgi.input'], environ=os.environ)
  File "/usr/lib64/python2.4/UserDict.py", line 17, in __getitem__
    def __getitem__(self, key): return self.data[key]
KeyError: 'wsgi.input'

Is it because wsgi.input does not exist in my version?

+4  A: 

You're misusing the WSGI API.

Please create a minimal ("hello world") function that shows this error so we can comment on your code. [Don't post your entire application, it may be too big and unwieldy for us to comment on.]

The os.environ is not what you should be using. WSGI replaces this with an enriched environment. A WSGI application gets two arguments: one is a dictionary that includes 'wsgi.input'.


In your code...

def application(environ, start_response):

    try:
        f = cgi.FieldStorage(fp=os.environ['wsgi.input'], environ=os.environ)

Per the WSGI API specification (http://www.python.org/dev/peps/pep-0333/#specification-details), don't use os.environ. Use environ, the first positional parameter to your application.

The environ parameter is a dictionary object, containing CGI-style environment variables. This object must be a builtin Python dictionary (not a subclass, UserDict or other dictionary emulation), and the application is allowed to modify the dictionary in any way it desires. The dictionary must also include certain WSGI-required variables (described in a later section), and may also include server-specific extension variables, named according to a convention that will be described below.

S.Lott
Pasted some more elaborate sample code. Please let me know I should change it.
nbolton
Ah, I didn't see that environ was an argument of my method. Silly mistake I think.
nbolton