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.
}))