Django异步更新单个页面模板 [英] Django async update a single page template

查看:204
本文介绍了Django异步更新单个页面模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有此功能的django视图,用于获取模板的数据:

I have a django view with this function to get the data for a template:

def get_context_data(self, **kwargs):
  context = super(MyView, self).get_context_data(**kwargs)
  context['extra_data'] = a_long_running_function()
  return context

extra_data显示在表格中.如上述功能所示,由于计算extra_data,页面加载时间很长.

The extra_data is displayed in a table. As the above function indicates, the page takes a long time to load due to calculation of extra_data.

那么我该如何立即显示页面,然后在计算extra_data时更新表格?

So how can I show the page straight away, and then update the tablewhen extra_data is computed?

我了解如何使用celery来使a_long_running_function异步执行,但是我不知道如何使页面(现在已加载,但表中缺少数据),获取该数据并自动更新?/p>

I understand how I can use celery to make a_long_running_function execute asynchronously, but I dont know how to then make the page (which is now loaded, but missing data for the table), get that data and update automatically?

推荐答案

如果您打算进行芹菜种植,则需要2个视图:

If you plan in going ahead with celery, you will need 2 views:

1. viewA加载主页(没有extra_data-可能在HTML中放置了旋转的gif动画,以传达给用户页面中仍有数据要加载).此视图还将启动celery任务(但不会等待它完成).它看起来类似于:

1.viewA that loads the main page (without the extra_data - maybe a spinning gif animation in it's place in the HTML, to convey to the user that there is still data to be loaded in the page). This view will also start the celery task (but will not wait for it to complete). It would look similar to:

def viewA(request):
    task = a_long_running_function.delay()

    return render_to_response('viewA.html', {'task_id': task.id})

2. viewB,将在用户浏览器加载viewA之后通过AJAX访问(目的是提供extra_data未被viewA加载的).它看起来类似于:

2.viewB that will be accessed via AJAX after the user's browser loads viewA (it's purpose will be to provide the extra_data which was not loaded by viewA). It would look similar to:

def viewB(request, task_id):
    extra_data = a_long_running_function.AsyncResult(task_id) 

    if extra_data.ready():
       return render_to_response('viewB.html', {'extra_data': extra_data.get()})

    return HttpResponse('')

用户的浏览器完成加载viewA后,您将需要一些JavaScript才能开始运行

Once the user's browser finishes loading viewA, you will need a bit of javascript to start running AJAX requests every X seconds/minutes to viewB to attempt to retrieve the celery task result (based on the celery task id that is available). Once the AJAX request successfully retrieves the task result from viewB, it can make it visible to the user.

这篇关于Django异步更新单个页面模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆