使用 Django 和 Celery 实现动态页面

rub*_*bik 5 html python django dynamic django-celery

我在我的tasks.py文件中注册了一个 Celery 任务。当有人 POST 到 /run/pk 时,我使用给定的参数运行任务。此任务还执行其他任务(普通 Python 函数),我想在子任务完成其工作时更新我的​​页面(在 /run/pk 处返回的 HttpResponse)。

这是我的任务:

from celery.decorators import task


@task
def run(project, branch=None):
    if branch is None:
        branch = project.branch
    print 'Creating the virtualenv'
    create_virtualenv(project, branch)
    print 'Virtualenv created' ##### Here I want to send a signal or something to update my page
    runner = runner(project, branch)
    print 'Using {0}'.format(runner)
    try:
        result, output = runner.run()
    except Exception as e:
        print 'Error: {0}'.format(e)
        return False
    print 'Finished'
    run = Run(project=project, branch=branch,
                       output=output, **result._asdict())
    run.save()
    return True
Run Code Online (Sandbox Code Playgroud)

Spi*_*ike 3

不幸的是,使用 Django 将推送通知发送到客户端的浏览器并不容易。最简单的实现是让客户端不断轮询服务器以获取更新,但这会大大增加服务器必须完成的工作量。以下是对不同选项的更好解释:

Django 将 HTTP 响应推送给用户

如果您没有使用 Django,则可以使用 websockets 来发送这些通知。然而 Django 并不是为使用 websockets 而构建的。这里很好地解释了为什么会这样,以及一些关于如何使用 websocket 的建议:

使用 websockets 和 python / django 进行操作(/扭曲?)