我试图实现StreamingHttpResponse,但遇到了一个乏味的问题。在大约2个页面请求之后,Web服务器停止响应,连接似乎就建立起来了。我真的很困惑是什么导致了这个问题。如果它与无限循环相关联,那么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
base.html
var 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)
我的主机提供商是Pythonywhere
这里可能会发生一些事情。SIGPIPE错误表明浏览器正在关闭连接,或者连接正在超时(Pythonywhere上打开的连接有5分钟的限制)。当连接打开超过5分钟时,您的web应用可能会重新启动,因此有一些代码可以在5分钟限制之前断开连接并重建连接,这将防止这种情况发生。另一种可能性是,你的员工正在流失。每个流将占用一个辅助进程,不管它打开多长时间,您都需要至少一个辅助进程来处理普通请求
相关问题 更多 >
编程相关推荐