将对象 id 参数移动到consumers.py Django-Channels

发布于 2025-01-18 23:14:36 字数 1715 浏览 1 评论 0原文

我有问题。关键是我正在使用Django后端进行申请,并反应前端。我想制作一个允许在Live-Chat Rooms写作的Websocket。问题是我不知道如何加载动态室ID。生病尝试解释。关键是ChatConsumer类中的Connect方法将加载消息将消息带入房间,并将其通过JSON发送到Frontend。

这就是外观。

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试图从我的视图中发送此ID,在那里我拥有由generics.retrieveapiview构建的RoomRetrieveView。 这是:

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

我试图将此室内变量从get_serializer_context移动到我的消费者.py文件,但它希望我放置“自我”属性,但我不知道如何弄清楚。我还尝试使用get_object方法,但也无法正常工作。我不知道。我还试图使用Global从方法中制作可变全球,但它仍然无法正常工作。当我试图从views.py文件中导入任何内容并做一些我得到的事情

 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'

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'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亽野灬性zι浪 2025-01-25 23:14:37

您可以在URL中使用房间ID并使用:self.room_name = self.scope ['url_route'] ['kwargs'] ['iD']也避免在消费者中使用阻止代码,通过在单独的方法中编写查询并使用database_sync_to_async作为装饰器,请使用async orm调用。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文