我有一个带有 python/flask 的 REST API 后端,并希望在事件流中流式传输响应。一切都在带有 nginx/uwsgi ( https://hub.docker.com/r/tiangolo/uwsgi-nginx-flask/ )的 docker 容器中运行。
API 工作正常,直到涉及事件流。似乎某些东西(可能是 nginx)正在缓冲“收益”,因为在服务器完成计算并将所有内容一起发送之前,任何类型的客户端都没有收到任何内容。
我尝试使用附加配置(nginx_streaming.conf)文件来调整 nginx 设置(根据 docker 映像说明):
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)