Как отправить данные из websocket в django consumer.py

Я пытаюсь отправить текущего пользователя в качестве аргумента в websocket при подключении, но не могу получить пользователя в функции websocket connect. пожалуйста, найдите код ниже.

consumer.py

import asyncio
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async

class ChatConsumer(AsyncConsumer):

    async def websocket_connect(self, event):
        self.connected = True
        print("connected", event)
        await self.send({
            "type": "websocket.accept"
        })

        while self.connected:
            User=event["username"] #tring to receive the current user
            await asyncio.sleep(2)
            apps = await database_sync_to_async(list)(User.objects.filter(user=User)
            listo=[]
            for app in apps:
                username = app.username
                id = app.id
                outputDict = {"id":id,"username":username}
                listo.append(outputDict) 
 
            await self.send({
                'type': 'websocket.send',
                'text': json.dumps(listo),
            })

    async def websocket_receive(self, event):
        print("receive", event)

    async def websocket_disconnect(self, event):
        print("disconnected", event)
        self.connected = False

javascipt:

var socket = new WebSocket('ws://'
+ window.location.host
+ '/ws/notif/'
+ socketCode
+ '/');

socket.onmessage = function(e){
    console.log("message", e.data);
};
socket.onopen = function(e){
    socket.send(JSON.stringify({
        'user': 1003, #trying to send user
    }))
    console.log("open", e);
};
socket.onerror = function(e){
    console.log("error", e)
};
socket.onclose = function(e){
    console.log("close", e)
};
}

Помогите пожалуйста как получить данные из JavaScript в websocket connect function

Вернуться на верх