4

I have created a socket with Django channels that return the serialized data of Category Object. But in the response, there is no full URL(the IP address is not there). This problem is similar to this question Django serializer Imagefield to get full URL. The difference is that I am calling the Serializer from a Consumer(Django Channels). Whereas in the link, Serializer is called from a View. In a Consumer, there is no request object as mentioned in the solution. The Django Channels says that scope in Consumers is similar to request in Views. So how can I get the full image url in this case?

Abhijith Konnayil
  • 4,067
  • 6
  • 23
  • 49

1 Answers1

0

The Django Channels says that scope in Consumers is similar to request in Views. Correct; therefore it depends how to setup your events in the AsyncConsumer. If you could share more about your code or a better explanation with a dummy example.

In general:
Import the serializers in the consumers and then send the same data to the serializers as shown below.

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

To fetch data from a websocket request:
Setup a receive event (ie channel-layer will receive the data) wherein it would trigger a particular event[for example I will implement to simply display that data]

#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}")

You can make the websocket request in the following way:-
create a new python file

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.
   }))
Chinmay Dali
  • 375
  • 5
  • 14