在Gunicorn中,如何添加连接:关闭服务器关闭后的响应?

时间:2017-04-12 10:08:05

标签: http nginx wsgi gunicorn

我知道Gunicorn中的on_exit挂钩,但不知道如何或是否可以使用它来添加"连接:关闭" HTTP标头到最终响应。

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

1 个答案:

答案 0 :(得分:1)

Gunicorn提供了工作挂钩,可以在此实例中用于在工作人员关闭时发送Connection:close标头。在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将标题存储为元组列表,因此更容易转换为dictonary,覆盖/插入CONNECTION标头并作为元组列表重新放入对象中。