Skip to main content
 首页 » 编程设计

python之Docker 图像中的 nginx 缓冲 flask 事件流

2025年01月19日35lori

我有一个带有 python/flask 的 REST API 后端,我想在事件流中流式传输响应。一切都在带有 nginx/uwsgi ( https://hub.docker.com/r/tiangolo/uwsgi-nginx-flask/ ) 的 docker 容器中运行。

在涉及到事件流之前,API 工作正常。似乎有什么东西(可能是 nginx)在缓冲“ yield ”,因为在服务器完成计算并将所有内容一起发送之前,任何类型的客户端都不会收到任何东西。

我尝试使用附加配置 (nginx_streaming.conf) 文件调整 nginx 设置(根据 docker image 说明):

server { 
  location / { 
        include uwsgi_params; 
        uwsgi_request_buffering off; 
  } 
} 

码头文件:

FROM tiangolo/uwsgi-nginx-flask:python3.6 
COPY ./app /app 
COPY ./nginx_streaming.conf /etc/nginx/conf.d/nginx_streaming.conf 

但我不太熟悉 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) 

请您参考如下方法:

我遇到了同样的问题。尝试改变

return Response(calcResult(), content_type="text/event-stream") 

到

return Response(calcResult(), content_type="text/event-stream", headers={'X-Accel-Buffering': 'no'})