0

感谢大家阅读我的第一篇文章。使用 Django 2.02,Django-channels 2.02。

我希望将从前端发送到后端的信息存储到 Django 会话存储中。我的问题是,只要 WebSocket 打开,Django-channels 会话范围似乎只存储信息,但我需要它像 Django http-session 一样存储它。

第一个来自前端 index.html 的 javascript。

<script>
const conn = new WebSocket('ws://localhost:8000/');

var msg = {
    type: "message",
    message: "Trying to find a solution",
    date: Date.now(),
};

msg = JSON.stringify(msg);
conn.onopen = () => conn.send(msg);
</script> 

消费者.py

from channels.generic.websocket import JsonWebsocketConsumer
from importlib import import_module
from django.conf import settings
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
#Have tried SessionStore to store but will also not work

class ConnectConsumer(JsonWebsocketConsumer):
    def connect(self):
        self.accept()

    def receive(self, text_data=None):
        text = self.decode_json(text_data) #decode incoming JSON
        text_message = text.get('message') 

        print(self.scope["session"]["message"]) #prints "None"
        self.scope["session"]["message"] = text_message
        self.scope['session'].save()
        print(self.scope["session"]["message"]) #prints "Trying to find a solution"

    def disconnect(self, message):
        pass

路由.py

from django.urls import path
from channels.http import AsgiHandler
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from consumers import ConnectConsumer

application = ProtocolTypeRouter({
    "websocket": AuthMiddlewareStack(
        URLRouter([
            path("/", ConnectConsumer),
        ]),
    )
})

视图.py

from django.shortcuts import render

def index(request):
    print(request.session.keys()) #returns Empty dict([])
    return render(
        request,
        'index.html',
    )

请告诉我这个问题是否广泛或我缺少相关信息。

4

2 回答 2

0

尝试将您的views.py代码更改为

from django.shortcuts import render

def index(request):
    if not 'message' in request.session.keys():
        request.session['message'] = ''
        print("'message' key created in HTTP session")    
    print(request.session['message']) # it should print "" on the first run
                                      # and "Trying to find a solution" after that
    return render(
        request,
        'index.html',
    )

我不太确定导致此问题的原因,但我想这与SessionMiddleware工作方式有关。似乎该SessionStore.save()方法在consumers.py. 这就是为什么我在views.py.


编辑 1 - 我的consumers.py

from channels.generic.websocket import JsonWebsocketConsumer
#from importlib import import_module
from django.conf import settings
#SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
#Have tried SessionStore to store but will also not work

class ConnectConsumer(JsonWebsocketConsumer):
    def connect(self):
        self.accept()

    def receive(self, text_data=None):
        text = self.decode_json(text_data) #decode incoming JSON
        text_message = text.get('message') 

        print(self.scope["session"]["message"]) 
        self.scope["session"]["message"] = text_message
        self.scope['session'].save()
        print(self.scope["session"]["message"]) #prints "Trying to find a solution"

    def disconnect(self, message):
        pass
于 2018-03-01T05:23:30.907 回答
0

我知道这个线程有点老了,但是我花了一整天的时间来弄清楚为什么没有通过 websocket 连接发送 cookie,因此我无法访问消费者中的正确会话。原来我只需要更换

new WebSocket('ws://localhost:8000/');

new WebSocket('ws://127.0.0.1:8000/');

除此之外,首先将会话或新会话密钥保存在消费者之外(例如在视图中)确实很重要,如@bjbschmitt 答案中所示。

我希望这会为某人节省很多时间。

于 2021-04-24T12:34:49.493 回答