我正在嘗試實現 StreamingHttpResponse 但遇到了一個繁瑣的問題。連接似乎已建立,然后在大約 2 個頁面請求后,網絡服務器停止響應。我真的很困惑是什么導致了這個問題。如果它與無限循環相關聯,則 time.sleep() 方法應該可以防止服務器立即過載。我將不勝感激任何幫助,謝謝!views.py: def event_stream(): initial_data = "" while True: data = json.dumps(list(Notification.objects.filter(to_user=1).order_by("-created_date").values("info", "return_url", "from_user","to_user","created_date")), cls=DjangoJSONEncoder) if not initial_data == data: yield "\ndata: {}\n\n".format(data) initial_data = data time.sleep(1)class PostStreamView(View): def get(self, request): response = StreamingHttpResponse(event_stream()) response['Content-Type'] = 'text/event-stream' return response基本.htmlvar eventSource = new EventSource("{% url 'stream' %}");eventSource.onopen = function() { console.log('We have open connection!'); } eventSource.onmessage = function(e) { console.log(e) } eventSource.onerror = function(e) { console.log(`error ${e}`); }</script>服務器日志:2020-10-20 19:25:51 Tue Oct 20 19:25:51 2020 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /AP%20Psychology/ (ip 10.0.0.124) !!!2020-10-20 19:25:51 Tue Oct 20 19:25:51 2020 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during GET /AP%20Psychology/ (10.0.0.124)2020-10-20 19:27:33 Tue Oct 20 19:27:33 2020 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /post/12/ (ip 10.0.0.124) !!!2020-10-20 19:27:33 Tue Oct 20 19:27:33 2020 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during GET /post/12/ (10.0.0.124)我的托管提供商是 PythonAnywhere
1 回答

慕俠2389804
TA貢獻1719條經驗 獲得超6個贊
這里可能會發生一些事情。SIGPIPE 錯誤表明瀏覽器正在關閉連接或連接超時(PythonAnywhere 上的打開連接有 5 分鐘限制)當連接打開超過 5 分鐘時,您的 Web 應用程序可能會重新啟動,因此有些代碼會在 5 分鐘限制之前中斷連接并重建連接,這樣可以防止這種情況發生。另一種可能性是你的工人已經用完了。每個流都會占用一名工作人員,無論其打開時間有多長,并且您至少需要一名工作人員來處理普通請求。
添加回答
舉報
0/150
提交
取消