使用 daphne 运行 channel 。
django version: 2.0.4
asgiref==2.2.0
asgi-redis==1.4.3
channels==2.1.5
channels-redis==2.3.1
我正在尝试连接 websoket。当我尝试连接匿名用户(没有用户登录)时,它运行良好。但是,当有用户时,它就不能很好地工作。
我通过使用 pdb.set_trace()
得到的一点是当我尝试时有 self.scope['cookies']['sessionid']
与用户登录。但是当没有用户(匿名用户)时,self.scope['cookies']['sessionid']
没有结果
我认为它可能与 AuthMiddlewareStack
有关,我查看了源代码。但是,我找不到问题的根源。
你能帮帮我吗? 以下是我的代码。
设置.py
ASGI_APPLICATION = 'businessproject.routing.application'<p></p> <p>CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } </p>
模型.py
class MyUser(AbstractUser):
galaxy_num=models.IntegerField(default=1)
onoff=models.IntegerField(default=1, null=True)<p></p>
<pre><code>def __str__(self):
return self.username
</code></pre>
<p></p>
- 消费者.py
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
import json, pdb
from asgiref.sync import async_to_sync<p></p>
<p>class TestConsumer(AsyncWebsocketConsumer):</p>
<pre><code>async def connect(self):
# Join room group
self.group_name="likes"
await self.channel_layer.group_add(
self.group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(
self.group_name,
self.channel_name
)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
await self.channel_layer.group_send(
self.group_name,
{
'type': 'like_message',
'message': message
}
)
# Receive message from room group
async def like_message(self, event):
message = "%s님이 게시물을 좋아합니다."%event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
</code></pre>
<p></p>
- 路由.py
<p></p>
<pre><code>from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from cebula import routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
routing.websocket_urlpatterns
)
),
})
</code></pre>
<p></p>
这是控制台结果
WebSocket 连接到 ws://127.0.0.1:8000/ws/test/
失败:WebSocket 握手期间出错:net::ERR_CONNECTION_RESET
如果您需要更多信息,请告诉我。
最佳答案
我自己解决了这个问题。
具体原因我也不知道
但是如果你在 routing.py 中删除 AuthMiddlewareStack
一切正常。
如果有人知道原因,请告诉我。
关于python - django channels 仅在尝试使用 User_login 时出现连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53170621/