python - 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
解决方案
这里可能会发生一些事情。SIGPIPE 错误表明浏览器正在关闭连接或连接超时(在 PythonAnywhere 上打开连接有 5 分钟的限制)当连接打开超过 5 分钟时,您的 Web 应用程序可能会重新启动,因此有一些代码会在 5 分钟限制之前断开连接并重建它,可以防止这种情况发生。另一种可能性是你的工人用完了。每个流都会占用一个工作人员,无论它打开多久,您都需要至少一个工作人员来处理普通请求。
推荐阅读
- javascript - 如何在 Laravel 刀片文件中使用 jquery 将选项附加到动态创建的选择元素
- solr - 如何拥有具有多个子约束的嵌套父查询
- visual-studio-code - 如何更改变音符号内的文本颜色?
- python - 如何将 seaborn 分布的 y 轴显示为百分比
- php - 为什么我在 Laravel Http 客户端中的“application/x-www-form-urlencoded”请求不起作用
- php - Symfony - 从安全路径中排除特定路由
- c# - 如何在 .Net 6 中创建测试服务器?
- python - 使用标准 csv.reader 方法拆分 CSV 文件
- c - SD卡SPI接口写入响应无效
- android - 尽管设置为 targetSDK 31,但 Flutter App 无法从 Google 商店为 Android 12 安装