Femme Fatale
Femme Fatale

Reputation: 880

Saving data Django Channels 2

I am trying to save the data which i am receiving from my client using the Django Channels.

I have read the documentation but its not very clear.

Here is my code of consumer.py

 def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

        # Receive message from room group

    def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        message2 = message[1]
        self.save_data(message2)
        self.send(text_data=json.dumps({
            'message': message2
        }))

    @database_sync_to_async
    def save_data (self, message):
        return DeviceLogs.objects.create(voltage=message)

As you may have noticed that i just want to save message2 in database.

Upvotes: 1

Views: 2652

Answers (2)

mehamasum
mehamasum

Reputation: 5742

Looks like your consumer extends WebsocketConsumer (sync consumer). If that is the case, remove the @database_sync_to_async decorator and it should be fine. You only need to do that if your consumer is async.

From the docs:

The Django ORM is a synchronous piece of code, and so if you want to access it from asynchronous code you need to do special handling to make sure its connections are closed properly.

If you’re using SyncConsumer, or anything based on it - like JsonWebsocketConsumer - you don’t need to do anything special, as all your code is already run in a synchronous mode and Channels will do the cleanup for you as part of the SyncConsumer code.

If you are writing asynchronous code, however, you will need to call database methods in a safe, synchronous context, using database_sync_to_async.

Upvotes: 1

Davit Tovmasyan
Davit Tovmasyan

Reputation: 3588

Not sure what's the problem in your code but this should work for you.

async def chat_message(self, event):
    ...
    message2 = message[1]
    await self.save_message(message2)
    ...

@database_sync_to_async
def save_message(self, message):
        ... save message here

Upvotes: 2

Related Questions