Django-channels 可以与 celery 共存吗

lon*_*ght 2 django celery channels

如果我用 Django 频道(nginx + 频道,我喜欢它的 websocket 功能)组成一个网站,我是否仍然可以像其他普通的 django 项目一样添加一些在后台运行的芹菜应用程序/任务?

Rob*_* Lu 5

是的,您可以同时使用两者。

例如https://vincenttide.com/blog/1/django-channels-and-celery-example/

  • 在浏览器端

您创建 websocket,服务器发送实时消息。

https://github.com/VincentTide/django-channels-celery-example/blob/6ddc5ace0e1b99031ad0505ba0ec20be3f87704d/templates/jobs/index.html#L73

  • 在消费者方面

您收到请求,创建任务(并告诉哪个频道要回复)。

@channel_session
def ws_receive(message):
    job.delay(message.reply_channel.name)
Run Code Online (Sandbox Code Playgroud)
  • 在芹菜工人

您收到任务,运行它。并通过达芙妮向浏览器发送实时消息。

@app.task
def job(reply_channel):
    Channel(reply_channel).send({
        "text": json.dumps ({
            "action": "completed",
        })
    })
Run Code Online (Sandbox Code Playgroud)