在 Gunicorn 中,如何在服务器关闭开始后将 Connection: Close 添加到响应中?

In Gunicorn, how can I add Connection: Close to the response once server shutdown has begun?

我知道 Gunicorn 中的 on_exit 挂钩,但不确定如何或是否可以使用它来向最终响应添加 "Connection: Close" HTTP header ).

我需要这个的原因是通知上游 Nginx 代理关闭,否则 Nginx 会给出“502 Bad Gateway”错误。

Gunicorn 提供了 worker hooks,在这种情况下可以使用它来发送 Connection: close header 当 workers 关闭时。在您的 gunicorn.conf 文件中尝试以下挂钩:

def pre_request(worker, req):

    if not worker.alive:
        header_dict = dict(req.headers)
        header_dict['CONNECTION'] = 'close'
        req.headers = header_dict.items()

Gunicorn 将 headers 存储为元组列表,因此更容易转换为字典,overwrite/insert CONNECTION header 并放回 object 作为完成后的元组列表。