Django:通过websocket定期发送更新 [英] Django: Send regularly updates over websocket
问题描述
我们目前正在使用django和django-omnibus(websockets)开发一个应用程序.我们需要通过websockets从服务器(django)定期向所有连接的客户端发送更新.
We are currently developing an application with django and django-omnibus (websockets). We need to send regularly updates from the server (django) to all connected clients via websockets.
问题是,我们不能使用cron或其他相关工具来完成这项工作.我已经写了一个manage.py命令,但是由于某些限制,如果通过python manage.py updateclients启动,似乎多功能无法将消息发送到websocket.
The problem is, that we can't use cron or something related to do the work. I've written a manage.py command but through some limitations it seems omnibus can't send the message to the websocket if launcher by python manage.py updateclients.
我知道django不是为这种东西设计的,但是有没有办法在正在运行的django实例本身中发送更新?
I know that django is not designed for this kind of stuff but is there a way to send the updates within the running django instance itself?
感谢帮助!
推荐答案
是因为您的托管环境没有 cron
而不能使用 cron
的原因吗?...或因为如果使用python manage.py启动器,似乎综合无法将消息发送到websocket"?
Is the reason you can't use cron
because your hosting environment doesn't have cron
? ...or because "it seems omnibus can't send the message to the websocket if launcher by python manage.py" ?
If you simply don't have cron
then you need to find an alternative such as https://apscheduler.readthedocs.org/en/latest/ or Celery also provides scheduled tasks.
但是如果问题是另一面:一种在正在运行的django实例本身中发送更新的方法",那么我建议一个简单的选择是将HTTP API添加到您的Django应用中.
But if the problem is the other side: "a way to send the updates within the running django instance itself" then I would suggest a simple option is to add an HTTP API to your Django app.
例如:
# views.py
from django.core.management import call_command
def update_clients(request):
call_command('updateclients')
return HttpResponse(status=204)
然后在您的crontab上,您可以执行以下操作:
Then on your crontab you can do something like:
curl 127.0.0.1/internalapi/update_clients
...,这样,您的 updateclients
代码就可以在与通向龙卷风服务器的活动连接中的Django实例中运行.
...and this way your updateclients
code can run within the Django instance that has the active connection to the omnibus tornado server.
您可能希望通过您的Web服务器或类似的方式对此URL进行一些访问控制:
https://djangosnippets.org/snippets/2095/
You probably want some access control on this url, either via your webserver or something like this:
https://djangosnippets.org/snippets/2095/
这篇关于Django:通过websocket定期发送更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!