【问题标题】:How can I render html page of Django after the background celery task is completed后台芹菜任务完成后如何渲染Django的html页面
【发布时间】:2017-12-08 22:11:15
【问题描述】:

问题:我正在使用带有 celery 的 rabbitmq 服务器

  1. 我需要在后台运行多个任务。我能做到的
  2. 当每个任务完成后,我需要渲染 html 页面,运行 html 页面我需要请求对象作为参数,celery 任务无法访问
  3. 当 celery 任务完成时,我已经脱离了具有请求对象的函数

未来 导入 unicode_literals、absolute_import 从 django.shortcuts 导入渲染 从 celDemo.celery 导入应用程序 进口时间 从 django.http.response 导入 HttpResponseRedirect # 在此处创建您的视图。

dictionary = {}
msg = "Hello!"

def testing(request):

    print 'In 1st page:'
    return render(request,'index.html')

def testcelery(request):

    print 'In testcelery'

    if request.method == 'POST':
        print 'On click event'
        value = str(request.POST['variable'])
        print request
        dictionary[value] = request
        print dictionary[value]
        try:
            make_wait.delay(value)
            return render(request,'index.html')
        except:
            return render(request,'nothing.html')

@app.task
def make_wait(value):
    print dictionary
    print msg
    print 'Started sleeping :)'
    actual2()
    print 'Slept :D'
    #request = dictionary[value]
    print value
    print 'before initiaing the request'
    return render('nothing.html')
    print 'after initiating the request'
    #return value


def actual2():
    result = actual()
    return result


def actual():
    time.sleep(25)
    return 'slept :D'

【问题讨论】:

    标签: django python-2.7 django-views rabbitmq django-celery


    【解决方案1】:

    在实际发出 POST 请求之前,您可以使用 AJAX 获取 nothing.html 的内容。将正文替换为获取的nothing.html 的内容,然后发出POST 请求,该请求将返回index.html 的内容。将正文替换为收到的index.html 的最终 html。

    示例代码:

    // js
    <script>
      $.ajax({
        url: 'url_to_get_nothing_html',
        type: 'GET',
        success: function(data) {
          $('body').html(data);
          $.ajax({
            url: 'url_to_index_html',
            type: 'POST',
            data: <data>,
            success: function(data) {
              $('body').html(data);
            }
        }
    </script>
    

    【讨论】:

    • 谢谢萨钦。但我的问题是 make_wait.delay(value) return render(request,'index.html') # 我无法返回这个渲染页面,因为我在后台进程中。我无法理解 ajax 将如何帮助我。我只需要访问主要流程变量,并且我想在浏览器上返回 Html 页面
    • @SBNAB 在 celery 进程结束后,返回您可以在页面中替换的 index.html 的内容,而不是 return render ...
    • 是的。进行 ajax 调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2013-07-17
    • 2015-06-16
    • 2021-10-01
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多