尝试同时运行后台任务同时更新Django中的视图

问题描述 投票:0回答:2

我正在一个项目中分析实时数据并将其绘制在每10秒更新一次的图形中。

我一直在尝试制作这个小程序的django网络应用程序,但不确定如何:

  1. 运行后台任务,连续分析数据。
  2. 每10秒钟,将此新数据推送到视图上。或在视图中呈现此数据,而不会破坏需要连续分析的功能。

我可以看什么?谢谢。

编辑:拼写

python django matplotlib streaming
2个回答
0
投票

您应该重新考虑如何访问数据。

首先,您的数据应存储在安全的地方。例如,一个数据库(Sqlite是默认值,非常简单)。创建一个模型,然后让您的后台任务根据需要更新数据库。

除了默认的URI,还有第二个URi,它以JSON格式返回数据(JsonResponse中的django.http对于此非常有用)。这样,客户端可以查询该地址并获得JSON数据作为响应。

第二,异步运行JavaScript脚本以调用上面的URI并根据需要更新屏幕上的元素。

这样,用户可以停留在页面上并进行更新,而无需每隔10秒钟重新绘制整个页面。

请注意,代码不是完整的,但是要给出基本的想法,您不应该原样使用(它很可能会失败)

views.py

from django.shortcuts import render
from django.http import JsonResponse
from django.forms.models import model_to_dict

def index(request):
  return render(request, "index.html")

def data(request):

  query = DataPoints.objects.all()
  datapoints= []
  for datapoint in query:
       datapoints.append(model_to_dict(datapoint ))
  data = {
        'datapoints' : datapoints
  }
  return JsonResponse(data, safe=False)

在index.html中,有一个脚本

function fetch_data() {
  fetch('youraddress.com/data') //Fetch data from the address
  .then(response => response.json()) //get the JSON section from the response
  .then( updatePage(data) ); //Here you do whatever you need to update then page with the data
  .then(setTimeout(fetch_data(), 10000)); //Finally, set timeout for 10 seconds and call function again
}

现在您只需要在页面加载后调用fetch_data一次,它将每10秒调用一次


0
投票

@@ Mandemon答案解决了问题,但这不是以这种方式解决的好习惯。

如果新的可用数据服务器将自动发送到用户视图(Web浏览器),您在其中更新视图(HTML),则可以在项目中使用Web套接字。反复向服务器发出请求不是一个好主意。


您可以使用Django Channels 实现网络套接字。现在您可以看到实时数据馈送。


进一步阅读:

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

© www.soinside.com 2019 - 2024. All rights reserved.