[英]Flask, Gunicorn, Nginx :: IOError: [Errno 32] Broken pipe
我正在嘗試將項目從開發轉移到生產。 (在開發階段,我只使用Flask
,現在我用Nginx
在Gunicorn
后面運行它。)
我在服務特定頁面時songs.html
問題, songs.html
。
頁面正確加載虛擬變量( jukebox = [whatever]
),但在現實生活中我使用的是生成器,如下所示:
playlist= query_playlist(p)
jukebox = next(playlist)
return render_template('songs.html',
jukebox=jukebox)
並且此函數需要一段時間(比如2s)才能返回結果...但是沒有提供結果,並且進程只是在返回結果后掛起。
我像這樣運行應用程序:
(appenv)$gunicorn -c gconfig.py app:app
wsgi.ppy
from app import app as application
if __name__ == "__main__":
application.run(host='0.0.0.0')
gconfig.py:
workers = 16
worker_class = 'sync'
worker_connections = 1000
timeout = 120 # changed this from 30 up
keepalive = 2
nginx.conf ( brew
安裝)
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://127.0.0.1:8000/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
如果我使用python app.py
運行應用程序,請返回dev階段:
if __name__ == '__main__':
app.run(use_reloader=True, threaded=True, debug=True)
至少我得到以下回溯:
Error on request:
Traceback (most recent call last):
File "/Users/me/Documents/Code/Apps/app/appenv/lib/python2.7/site-packages/werkzeug/serving.py", line 270, in run_wsgi
execute(self.server.app)
File "/Users/me/Documents/Code/Apps/app/appenv/lib/python2.7/site-packages/werkzeug/serving.py", line 261, in execute
write(data)
File "/Users/me/Documents/Code/Apps/app/appenv/lib/python2.7/site-packages/werkzeug/serving.py", line 236, in write
self.send_header('Server', self.version_string())
File "/Users/me/anaconda2/lib/python2.7/BaseHTTPServer.py", line 412, in send_header
self.wfile.write("%s: %s\r\n" % (keyword, value))
IOError: [Errno 32] Broken pipe
那么有誰知道如何解決這個問題?
編輯
即使結果需要處理2秒,我也會獲得相同的回溯。
根據Flask docs (以及#arielnmz sugestion),您可以流式傳輸您的內容:
from flask import Response, stream_with_context
@app.route('/playlist')
def generate_playlist():
def generate():
jukebox = query_playlist(p)
for i in jukebox:
yield i[0]['artist']
return Response(stream_with_context(generate()))
每個yield表達式都直接發送到瀏覽器。
訣竅是有一個內部函數,它使用生成器生成數據,然后調用該函數並將其傳遞給響應對象。
這有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.