python - django channels 仅在尝试使用 User_login 时出现连接错误

标签 python django redis django-channels

使用 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 有关,我查看了源代码。但是,我找不到问题的根源。

你能帮帮我吗? 以下是我的代码。

  1. 设置.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>

  2. 模型.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>

  1. 消费者.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>

  1. 路由.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/

相关文章:

python - 使用 Python+Stomp.py 和 ActiveMQ 发送/接收图像

mysql - 在django中采样mysql结果

node.js - 如何使用 Redis 以原子方式增加值

node.js - Redis 中的 SQL 或 Oracle 表结构

python - 替换 pandas DataFrame 中的列值

python - 转换 GUI 状态

python - 在 django-rest-framework 中解析多部分/表单数据

javascript - redis 处理 'N' 没有连接的能力?

python - 修改jinja2中的字典属性

python - 路径不能包含斜杠