我在我的 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
最佳答案
不幸的是,使用 Django 向客户端浏览器发送推送通知并不容易。最简单的实现是让客户端不断轮询服务器以获取更新,但这会大大增加服务器必须完成的工作量。以下是对不同选项的更好解释:
Django Push HTTP Response to users
如果您不使用 Django,您会使用 websockets 来发送这些通知。然而,Django 并不是为使用 websockets 而构建的。这里很好地解释了为什么会这样,以及一些关于如何使用 websockets 的建议:
Making moves w/ websockets and python / django ( / twisted? )
关于python - 使用 Django 和 Celery 的动态页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8096247/