python - 在 Django Channel Response 上获取图像完整 url
问题描述
我创建了一个带有 Django 通道的套接字,它返回类别对象的序列化数据。但是在响应中,没有完整的 URL(IP 地址不存在)。这个问题类似于这个问题Django serializer Imagefield to get full URL。不同之处在于我从消费者(Django 频道)调用序列化程序。而在链接中,序列化程序是从视图中调用的。在消费者中,没有解决方案中提到的请求对象。Django Channels 说消费者中的范围类似于视图中的请求。那么在这种情况下如何获得完整的图片网址呢?
解决方案
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.
}))
推荐阅读
- javascript - 绝对元素的不同位置取决于使用的设备或浏览器
- bash - 将特定字符从文本文件的前两行复制到变量
- python - 使用 findall 的交流发电机中的字符串与正确的字符串不匹配
- javascript - js前端fetch()发布到rails后端文件路径到文件错误
- apache - 我想配置一个 Case InSensitive Web 服务器
- python - setuptools,提前知道原生库的wheel文件名
- javascript - 我如何强制浏览器(ie7)从请求中加载文件?
- html - 覆盖某些标签内的链接颜色
- java - 我想在活动中运行一次代码
- css - @supports CSS at-rule 不能正常工作