简体   繁体   中英

Moving object id parameter to consumers.py Django-Channels

I have a problem. The point is that I am making application with Django backend and React frontend. I wanted to make a websocket which allows to write in live-chat rooms. The problem is that I have no idea how to load dynamic a Room id. Ill try to explain. The point is that connect method from ChatConsumer class will load messages realted to room and send it by json to frontend.

Ths is how it looks.

class ChatConsumer(WebsocketConsumer):

    def connect(self):
        self.room_group_name = 'test'

        async_to_sync(self.channel_layer.group_add)(
          self.room_group_name,
          self.channel_name
        )
        messages = Message.objects.filter(room=[HERE I NEED TO PUT ID OF ROOM])
        data_ready_for_json =list( messages.values('room','body','user'))
        self.accept()
        self.send(text_data=json.dumps({
        'type':'chat',
        'message': data_ready_for_json

      }))

Iam trying to send this id from my views, where I have RoomRetrieveView built by generics.RetrieveAPIView. Here it is:

class RoomRetrieveView(generics.RetrieveAPIView):
    queryset = Room.objects.all()
    permission_classes = (AllowAny,)
    serializer_class = RoomSerializer


    def get_serializer_context(self):
        context = super(RoomRetrieveView,self).get_serializer_context()
        context.update({'id' : self.get_object().id})
        roomId = context['id']
        return roomId

I was trying to move this roomId variable from get_serializer_context to my consumers.py file but it wants me to put "self" attribute but I have no idea how to figure it out. I also tried to use get_object method but it also not working. I have no idea. I also tried to use global to make variable global from method but its still not working. When Im trying to import anything from views.py file and do something I am getting

 File "E:\Coding\Python\PORTFOLIO\Say-It-Social\venv\lib\site-packages\channels\routing.py", line 30, in get_default_application
    raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'sayitsocial.asgi'

You could use room id in the URL and retrive it using: self.room_name = self.scope['url_route']['kwargs']['id'] also avoid using a blocking code in consumers, use async ORM calls by writing the query in a separate method and use database_sync_to_async as a decorator you could import it from channels.db

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM