将Django-cookie sessionId链接到Channels 2.02连接?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将Django-cookie sessionId链接到Channels 2.02连接?相关的知识,希望对你有一定的参考价值。

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

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

来自前端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> 

consumers.朋友

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

routing.朋友

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),
        ]),
    )
})

views.朋友

from django.shortcuts import render

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

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

答案

尝试将您的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中预先分配'message'键。


编辑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

以上是关于将Django-cookie sessionId链接到Channels 2.02连接?的主要内容,如果未能解决你的问题,请参考以下文章

19)django-cookie使用

基于Django-Cookie的CBV和FBV的用户验证装饰器

将 SessionId 转换为用户帐户 SID _without_ WTSQuerySessionInformation?

asp.net sessionID 在回发时更改?

Android网络请求知识(三)授权,TCP/IP,HTTPS建立过程

移动端权限控制--设置每个登录用户的sessionId