Skip to main content
 首页 » 编程设计

python之为什么会出现错误,KeyError : 'wsgi.input'

2025年05月04日15bonelee

我正在使用 WSGI 并尝试访问获取/发布数据,使用以下代码:

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] 

但是我得到以下错误:

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' 

是不是我的版本没有wsgi.input?

请您参考如下方法:

您滥用了 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) 

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

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.