如何将频道和DRF集成在一起

时间:2019-01-24 16:06:27

标签: python django django-rest-framework django-channels

我目前正在尝试创建一个后端服务器,以通过websocket与某些客户端进行通信。客户端向后端发出一些请求,后端通过使用者直接响应客户端。

此外,我有一个API,需要向客户端发送一些请求。它必须穿过使用者打开的插座。我将Django Rest Framework用于API。所以我现在有2个应用程序。一种用于使用者,另一种用于API。我想知道这是否正确。

这实际上是我现在正在考虑的代码:

# mybackendapp/consumers.py

class MyConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.client_id = self.scope['url_route']['kwargs']['client_id']
        # This line I don't get it very well. It comes from:
        # [channels doc: single channels][1]
        # I don't know if I should create the Clients myself or if it's 
        # created automatically
        Clients.objects.create(channel_name=self.channel_name, 
                               self.client_id)
        self.accept()

    async def disconnect(self):
         Clients.objects.filter(channel_name=self.channel_name).delete()

    async def receive(self, text_data):
        self.recv_data = json.loads(text_data)
        if self.recv_data[0] == CLIENT_REQUEST:
            self.handler = ClientRequestHandler(self.client_id, 
                                                self.recv_data)
            await self.handler.run()
            self.sent_data = self.handler.response
            self.send(self.sent_data)
        elif self.recv_data[0] == CLIENT_RESPONSE:
            self.handler = ClientResponseHandler(self.client_id,
                                                 self.recv_data)
            channel_layer = get_channel_layer()
            # Here I'm not sure but I may have several API requests so
            # several row with the same client_id.
            # I welcome info on how to deal with that.
            api_channel_name = self.another_handler.ext_channel_name
            channel_layer.send(api_channel_name, {
                "text_data": self.handler.response,
            })

    async def message_from_api(self, event):
        self.api_channel_name = event['channel_name_answer']
        # this line is for hiding the fact that I'm only manipulating data
        # to send it to a correct format to the socket
        self.another_handler = ExternalDataHandler(event['json_data'])
        query_to_client = another_handler.get_formatted_query()
        self.send(query_to_client)

在接收过程中,此使用者处理来自客户端的消息的方式有所不同,具体取决于消息是由客户端还是其余API发起的。您可以使用CLIENT_REQUESTCLIENT_RESPONSE常量看到这一点。 现在从API视图中:

# myapi/views.py

from channels.layers import get_channel_layer

def my_api_view(request, client_id):
    channel_layer = get_channel_layer()
    if request.method == 'POST':
        ext_request_data_json = request.data
        client_channel_name = Clients.objects.get(
            client_id=client_id).channel_name
        # I don't know what type is listen_channel_name. I assume it's str
        listen_channel_name = async_to_sync(channels_layers.new_channel)()
        async_to_sync(channel_layer.send)(
            client_channel_name, {
                'type': 'message.from.api',
                'json_data': ext_request_data_json,
                'channel_name_answer': listen_channel_name
            }
        )
        received_msg = channel_layer.receive(listen_channel_name)

我认为此代码应该有效。我想知道这是否是正确的方法。

0 个答案:

没有答案