gpt4 book ai didi

python - uwsgi:发送http响应并继续执行

转载 作者:太空宇宙 更新时间:2023-11-03 21:09:08 28 4
gpt4 key购买 nike

来自 uwsgi 文档:

def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"]

是否可以响应http请求(关闭http连接)并继续执行流程(不使用任何线程/队列/外部服务等)?像这样:

def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
end_response(b"Hello World")
#HTTP connection is closed
#continue execution..

最佳答案

TL;DR - 如果您使用的是 Django,则可以跳到答案的末尾。

是的,有一种方法可以做到这一点。您可以 Hook 由您的 application 可调用对象返回的 .close() 方法(或者通过环境返回 wsgi.file_wrapper

检查 PEP333,特别是服务器端规范部分:https://peps.python.org/pep-0333/#the-server-gateway-side :

    result = application(environ, start_response)
try:
for data in result:
if data: # don't send headers until body appears
write(data)
if not headers_sent:
write('') # send headers now if body was empty
finally:
if hasattr(result, 'close'):
result.close()

如您所见,result.close() 将在最后调用,此时数据已发送。

当然,这只是一些引用代码,它不处理上游以及在继续执行之前终止连接。但行为良好的 wsgi 服务器,例如 uwsgi 和(大概)gunicorn,可以。它们将通过关闭套接字(或上游协议(protocol)所需的任何内容)向上游发出请求已完成发送的信号,然后然后调用.close()

如果你使用的是 Django,那么你已经设置好了,因为它有 request_finished信号。它的工作原理如下,它如上所述 Hook 到 .close():

https://github.com/django/django/blob/57c7220280db19dc9dda0910b90cf1ceac50c66f/django/http/response.py#L323

关于python - uwsgi:发送http响应并继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55187198/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com