为什么会出现错误 KeyError: 'wsgi.input'?

1 投票
1 回答
4150 浏览
提问于 2025-04-15 14:24

我正在使用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]

但是我遇到了以下错误:

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这个东西呢?

1 个回答

7

你在使用 WSGI API 的时候搞错了。

请写一个简单的“你好,世界”函数来展示这个错误,这样我们才能对你的代码进行评论。[不要发整个应用程序,因为可能太大了,我们不容易评论。]

你不应该使用 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,这是你应用程序的第一个位置参数。

environ 参数是一个字典对象,包含了 CGI 风格的环境变量。这个对象必须是 Python 内置的字典(不能是子类、UserDict 或其他字典模拟),而且应用程序可以随意修改这个字典。字典中还必须包含一些 WSGI 必需的变量(在后面的部分会描述),并且可能还会包含一些特定于服务器的扩展变量,这些变量的命名会在下面的部分中说明。

撰写回答