WSGI会覆盖`Content-Length`头吗?

1 投票
1 回答
1877 浏览
提问于 2025-04-16 04:58

HTTP的HEAD请求应该像GET请求一样包含Content-Length这个头信息。但是,如果我设置了Content-Length头,它会被WSGI环境覆盖(关于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

没有这样的配置选项。你需要去修改或覆盖 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()

撰写回答