【问题标题】:Get image full url on Django Channel Response在 Django Channel Response 上获取图像完整 url
【发布时间】:2021-04-05 17:54:58
【问题描述】:

我创建了一个带有 Django 通道的套接字,该通道返回类别对象的序列化数据。但在响应中,没有完整的 URL(IP 地址不存在)。这个问题类似于Django serializer Imagefield to get full URL这个问题。不同之处在于我从消费者(Django 频道)调用序列化程序。而在链接中,序列化程序是从视图中调用的。在消费者中,没有解决方案中提到的请求对象。 Django Channels 说消费者中的 scope 类似于视图中的 request。那么在这种情况下如何获取完整的图片url呢?

【问题讨论】:

    标签: python django django-channels


    【解决方案1】:

    Django Channels 说消费者中的范围类似于视图中的请求。 正确的;因此这取决于如何在 AsyncConsumer 中设置您的事件。 如果您可以通过虚拟示例分享更多关于您的代码或更好的解释。

    一般:
    在消费者中导入序列化器,然后将相同的数据发送到序列化器,如下所示。

    from <app_name>.serializers import <desired_serializer_name>Serializer
    from channels.db import database_sync_to_async
    
    @database_sync_to_async
    def serializer_checking_saving_data(self, data):
        serializer = <desired_serializer_name>Serializer(data=data)
        serializer.is_valid(raise_exception=True)
        x = serializer.create(serializer.validated_data)#this will create the value in the DB
        return <desired_serializer_name>Serializer(x).data
    

    从 websocket 请求中获取数据:
    设置一个接收事件(即通道层将接收数据),其中它将触发一个特定事件[例如我将实现简单地显示该数据]

    #write this inside the AsyncWebsocketConsumer
    async def receive_json(self, content, **kwargs):
        """[summary]
        • All the events received to the server will be evaluated here.
        • If websocket has event-type based on these the receive function will execute
            the respective function
        """
        message_type = content.get('type')
        if message_type == 'start.sepsis':
            await self.display_the_data(content)
        
    
    async def display_the_data(self,data)
        message = data.get('payload')
        print(f"The data sent to the channel/socket is \n {data}")
    

    您可以通过以下方式发出 websocket 请求:-
    创建一个新的python文件

    import json
    import websocket
    import asyncio
    async def making_websocket_request():
        ws_pat = websocket.WebSocket()
        ws_pat.connect(
            'ws://localhost:8000/<ws-router-url>/')
        asyncio.sleep(2)#it might take a couple of seconds to connect to the server
       ws.send(json.dumps({
           'type':'display.the_data'
           #the channels will convert "display.the_data" to "display_the_data"
           #since "display_the_data" their is an event as defined above it would be called
           'payload':{<can-be-any-json-data>}
           #this payload will be sent as a parameter when calling the function.
       }))
    

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 2013-04-06
      • 2021-10-29
      • 1970-01-01
      • 2022-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多