You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

django-eventstream调用send_event无数据返回问题求助

解决django-eventstream消息无法推送的问题

核心问题排查与修复步骤

1. 配置跨进程消息通道(必须)

django-eventstream默认使用内存通道,仅适用于单进程场景。shell命令、huey定时任务属于独立进程,和ASGI服务器进程无法共享内存消息,导致消息无法送达。必须配置Redis作为共享通道层:

  • 安装依赖:pip install channels-redis
  • 在settings.py中添加CHANNEL_LAYERS配置:
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}
  • 确保Redis服务正在运行。

2. 修正ASGI路由参数传递

你的asgi.py中路由参数传递方式错误,正确的做法是将通道参数通过scope传递,修改asgi.py如下:

from django.urls import path, re_path
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import django_eventstream

application = ProtocolTypeRouter({
    "http": URLRouter([
        path("msgs/", AuthMiddlewareStack(
            URLRouter(django_eventstream.routing.urlpatterns)
        ), {"channels": ["test"]}),
        re_path(r"", get_asgi_application()),
    ]),
})

同时,urls.py中不需要重复传递参数,简化为:

urlpatterns = [path("msgs/", include(django_eventstream.urls))]

3. 使用ASGI兼容的服务器启动

必须用支持ASGI的服务器运行项目,不能用Django默认的runserver(WSGI模式无法处理长连接):

uvicorn your_project.asgi:application --reload --port 8000

4. 验证huey任务的环境初始化

确保huey的worker正确加载Django配置,在huey的配置文件中添加:

from django.conf import settings
import django

django.setup()

启动huey worker时,确保处于Django项目的虚拟环境中:

python manage.py run_huey

5. 前端订阅验证

前端代码可添加错误监听排查问题:

var es = new ReconnectingEventSource('/msgs/');

es.addEventListener('message', function (e) {
    console.log('收到消息:', JSON.parse(e.data));
}, false);
es.addEventListener('error', function (e) {
    console.error('连接错误:', e);
}, false);
es.addEventListener('stream-reset', function (e) {}, false);

测试步骤

  1. 启动Redis服务
  2. 用uvicorn启动ASGI服务器
  3. 启动huey worker
  4. 打开浏览器访问项目,查看控制台是否收到定时任务推送的消息
  5. 在Django shell中测试:
from django_eventstream import send_event
send_event('test', 'message', {'text': 'hello'})

内容的提问来源于stack exchange,提问作者xtlc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:30:45