Python Docker映像中的nginx缓冲烧瓶事件流
我有一个带有python/flask的restapi后端,希望在事件流中传输响应。一切都在一个带有nginx/uwsgi()的docker容器中运行 API在进入事件流之前工作正常。似乎有什么东西(可能是nginx)在缓冲“收益”,因为在服务器完成计算并将所有内容一起发送之前,任何类型的客户端都不会收到任何内容 我试图通过一个额外的配置文件(nginx_streaming.conf)来调整nginx设置(根据docker图像说明),该文件说:Python Docker映像中的nginx缓冲烧瓶事件流,python,nginx,flask,event-stream,event-stream-processing,Python,Nginx,Flask,Event Stream,Event Stream Processing,我有一个带有python/flask的restapi后端,希望在事件流中传输响应。一切都在一个带有nginx/uwsgi()的docker容器中运行 API在进入事件流之前工作正常。似乎有什么东西(可能是nginx)在缓冲“收益”,因为在服务器完成计算并将所有内容一起发送之前,任何类型的客户端都不会收到任何内容 我试图通过一个额外的配置文件(nginx_streaming.conf)来调整nginx设置(根据docker图像说明),该文件说: server { location / {
server {
location / {
include uwsgi_params;
uwsgi_request_buffering off;
}
}
dockerfile:
但我对nginx的设置并不十分熟悉,我确信我在这里所做的^^至少这不起作用。。有什么建议吗
我的服务器端实现:
from flask import Flask
from flask import stream_with_context, request, Response
from werkzeug.contrib.cache import SimpleCache
cache = SimpleCache()
app = Flask(__name__)
from multiprocessing import Pool, Process
@app.route("/my-app")
def myFunc():
global cache
arg = request.args.get(<my-arg>)
cachekey = str(arg)
print(cachekey)
result = cache.get(cachekey)
if result is not None:
print('Result from cache')
return result
else:
print('object not in Cache...calculate...')
def calcResult():
yield 'worker thread started\n'
with Pool(processes=cores) as parallel_pool:
[...]
yield 'Somewhere in the processing'
temp_result = doSomethingWith(
savetocache = cache.set(cachekey, temp_result, timeout=60*60*24) #timeout in seconds
yield 'saved to cache with key:' + cachekey +'\n'
print(savetocache, flush=True)
yield temp_result
return Response(calcResult(), content_type="text/event-stream")
if __name__ == "__main__":
# Only for debugging while developing
app.run(host='0.0.0.0', debug=True, port=80)
从烧瓶导入烧瓶
从flask导入流_,带有_上下文、请求、响应
从werkzeug.contrib.cache导入SimpleCache
cache=SimpleCache()
app=烧瓶(名称)
从多处理导入池中,选择进程
@app.route(“/my app”)
def myFunc():
全局缓存
arg=request.args.get()
cachekey=str(arg)
打印(缓存键)
结果=cache.get(cachekey)
如果结果不是无:
打印('来自缓存的结果')
返回结果
其他:
打印('对象不在缓存中…计算…')
def calcResult():
产生“工作线程已启动\n”
将池(进程=核心)作为并行池:
[...]
“加工中的某个地方”的产量
温度结果=doSomethingWith(
savetocache=cache.set(cachekey,temp_结果,超时=60*60*24)#以秒为单位超时
yield“保存到缓存,密钥为“+cachekey+”\n
打印(savetocache,flush=True)
产量-温度-结果
返回响应(calcResult(),content\u type=“文本/事件流”)
如果名称=“\uuuuu main\uuuuuuuu”:
#仅用于开发时的调试
app.run(主机=0.0.0.0',调试=True,端口=80)
我遇到了相同的问题。请尝试更改
return Response(calcResult(), content_type="text/event-stream")
到
接下来,我将其添加到/etc/nginx/conf.d/mysite.conf
中,解决了问题:
add_header X-Accel-Buffering no;
我已经在位置/
下添加了它,但是将它放在事件流的特定位置下可能是一个好主意(我这里有一个低流量intranet用例)
注意:如果这个标题来自应用程序,那么nginx默认情况下可能会删除它:更习惯地说是在flask中——这就是OP正在使用的,您可以将它添加到@app.after_quest钩子中的请求中。下面的修复有帮助吗?我遇到了同样的问题,无法通过关闭缓冲来解决它。我没有“我还在找。
return Response(calcResult(), content_type="text/event-stream", headers={'X-Accel-Buffering': 'no'})
add_header X-Accel-Buffering no;