为什么我会收到错误,KeyError:'wsgi.input'?

Nic*_*ton 1 python mod-wsgi

我正在使用WSGI并尝试使用以下代码访问get/post数据:

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]
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

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'
Run Code Online (Sandbox Code Playgroud)

是因为我的版本中不存在wsgi.input吗?

S.L*_*ott 7

您滥用WSGI API.

请创建一个显示此错误的最小("hello world")函数,以便我们对您的代码进行评论.[不要发布你的整个申请,我们评论可能太大而且不实用.]

os.environ不是你应该使用的.WSGI用丰富的环境取而代之.WSGI应用程序有两个参数:一个是包含的字典'wsgi.input'.


在你的代码中......

def application(environ, start_response):

    try:
        f = cgi.FieldStorage(fp=os.environ['wsgi.input'], environ=os.environ)
Run Code Online (Sandbox Code Playgroud)

根据WSGI API规范(http://www.python.org/dev/peps/pep-0333/#specification-details),请勿使用os.environ.使用environ,作为应用程序的第一个位置参数.

environ参数是一个字典对象,包含CGI样式的环境变量.此对象必须是内置的Python字典(不是子类,UserDict或其他字典模拟),并且允许应用程序以任何方式修改字典.字典还必须包括某些WSGI所需的变量(在后面的部分中描述),并且还可以包括服务器特定的扩展变量,根据将在下面描述的约定命名.