首页 > 解决方案 > Django StreamingHttpResponse() 导致服务器停止工作

问题描述

我正在尝试实现 StreamingHttpResponse 但遇到了一个乏味的问题。连接似乎已建立,然后在大约 2 个页面请求后,网络服务器停止响应。我真的很困惑是什么导致了这个问题。如果它与无限循环相关联,则 time.sleep() 方法应该可以防止服务器立即过载。我会很感激任何帮助,谢谢!

视图.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)

我的托管服务提供商是 PythonAnywhere

标签: pythondjango

解决方案


这里可能会发生一些事情。SIGPIPE 错误表明浏览器正在关闭连接或连接超时(在 PythonAnywhere 上打开连接有 5 分钟的限制)当连接打开超过 5 分钟时,您的 Web 应用程序可能会重新启动,因此有一些代码会在 5 分钟限制之前断开连接并重建它,可以防止这种情况发生。另一种可能性是你的工人用完了。每个流都会占用一个工作人员,无论它打开多久,您都需要至少一个工作人员来处理普通请求。


推荐阅读