gpt4 book ai didi

Django channel 与 daphne 和worker 超时

转载 作者:行者123 更新时间:2023-12-01 18:36:20 26 4
gpt4 key购买 nike

我的 django channel 有问题。我的 Django 应用程序与 WSGI 完美运行以处理 HTTP 请求。我尝试迁移到 channel 以允许 websocket 请求,结果发现在安装 channel 并运行 ASGI (daphne) 和工作人员后,服务器回答错误 503,浏览器显示 http 请求的错误 504(超时)以前可以使用的内容(例如管理页面)。我阅读了我能找到的所有教程,但我不明白问题出在哪里。此外,如果我使用“runserver”运行,它工作得很好。

我在应用程序前面有一个 Nginx(在单独的服务器上),用作代理和负载平衡器。我使用 Django 1.9.5 和 asgi-redis>=0.10.0、channels>=0.17.0 和 daphne>=0.15.0。 wsgi.py 和 asgi.py 文件位于同一文件夹中。 Redis 正在工作。

我之前在 WSGI 中使用的命令(如果我切换回它仍然有效)是: uwsgi --http :8000 --master --enable-threads --module Cats.wsgi

使用 runserver 的命令是: python manage.py runserver 0.0.0.0:8000

与其他 2 个命令一起使用的请求失败的命令是: daphne -b 0.0.0.0 -p 8000 Cats.asgi:channel_layer
python manage.py runworker

其他信息:我在已安装的应用程序中添加了“ channel ”(在 settings.py 中)

其他settings.py相关信息

CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"ROUTING": "Cats.routing.app_routing",
"CONFIG": {
"hosts": [(os.environ['REDIS_HOST'], 6379)],
},
},

}

猫/routing.py

from channels.routing import route, include
from main.routing import routing as main_routing

app_routing = [
include(main_routing, path=r"^/ws/main"),
]

主/路由.py

from channels.routing import route, include

http_routing = [
]

stream_routing = [
route('websocket.receive', 'main.consumers.ws_echo'), #just for test once it will work
]

routing = [
include(stream_routing),
include(http_routing),
]

main/consumers.py

def ws_echo(message):
message.reply_channel.send({
'text': message.content['text'],
})

#this consumer is just for test once it will work

知道可能出了什么问题吗?非常感谢所有帮助!泰

编辑:我尝试了一个新事物:

python manage.py runserver 0.0.0.0:8000 --noworker
python manage.py runworker

这不起作用,而 python manage.py runserver 0.0.0.0:8000正在工作...

有什么想法可以帮忙吗?

最佳答案

channel 将使用默认 View 来处理未路由的请求。假设您正确使用 javascript,我建议您仅使用默认的 Cats/routing.py 文件,如下所示:

from channels.routing import route
from main.consumers import *


app_routing = [
route('websocket.connect', ws_echo, path="/ws/main")
]

或者用反向来帮助你的路径

from django.urls import reverse

from channels.routing import route
from main.consumers import *


app_routing = [
route('websocket.connect', ws_echo, path=reverse('main view name'))
]

我认为你的消费者也应该改变。当浏览器使用 websocket 连接时,服务器应首先处理添加消息回复 channel 。像这样:

def ws_echo(message):
Group("notifications").add(message.reply_channel)
Group("notifications").send({
"text": json.dumps({'testkey':'testvalue'})
})

发送功能可能应该在不同的事件上调用,并且“通知”组可能应该更改为拥有专用于用户的 channel 。类似的东西

from channels.auth import channel_session_user_from_http

@channel_session_user_from_http
def ws_echo(message):
Group("notify-private-%s" % message.user.id).add(message.reply_channel)
Group("notify-private-%s" % message.user.id).send({
"text": json.dumps({'testkey':'testvalue'})
})

关于Django channel 与 daphne 和worker 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com