WSGI是否覆盖`Content-Length`标题?

时间:2010-10-04 16:11:53

标签: python http http-headers wsgi

HTTP HEAD请求应包含Content-Length标头,就好像它们是GET个请求一样。但是,如果我设置了Content-Length标头,它将被WSGI环境(discussion related to mod_wsgi)覆盖。

看看下面的例子:

from wsgiref.simple_server import make_server

def application(environ, start_response):
    status = '200 OK'
    headers = [('Content-Type', 'text/plain'), ('Content-Length', '77')]
    start_response(status, headers)
    return []

httpd = make_server('', 8000, application)
print("Serving on port 8000...")
httpd.serve_forever()

...然后使用curl调用它:

$ curl -X HEAD http://localhost:8000/ -i
HTTP/1.0 200 OK
Date: Mon, 04 Oct 2010 16:02:27 GMT
Server: WSGIServer/0.1 Python/2.7
Content-Type: text/plain
Content-Length: 0                         <-- should be 77

如何告诉WSGI环境不要覆盖内容长度值?

1 个答案:

答案 0 :(得分:0)

没有这样的配置设置。您必须覆盖或修改wsgiref/handlers.py,如下所示:

from wsgiref.simple_server import make_server
from wsgiref.simple_server import ServerHandler
def finish_content(self):
    """Ensure headers and content have both been sent"""
    if not self.headers_sent:
        if (self.environ.get('REQUEST_METHOD', '') != 'HEAD' or
            'Content-Length' not in self.headers):
            self.headers['Content-Length'] = 0
        self.send_headers()
ServerHandler.finish_content = finish_content
def application(environ, start_response):
    status = '200 OK'
    headers = [('Content-Type', 'text/plain'), ('Content-Length', '77')]
    start_response(status, headers)
    return []
httpd = make_server('', 8000, application)
print("Serving on port 8000...")
httpd.serve_forever()