JayK23
JayK23

Reputation: 253

Save data to database from Django Channels consumer

I'm having an hard time editing a database entry from a Django channels consumer, here is the piece of code involved:

class TestConsumer(AsyncJsonWebsocketConsumer):

    async def websocket_connect(self, event):
        ...
        key_query.active_connections = 2
        key_query.save()
        ...

Since i'm using an asynchronous consumer, this will give me the following error:

You cannot call this from an async context - use a thread or sync_to_async.

How can i perform this action from an async consumer? Maybe using @database_sync_to_async?Any advice is appreciated!

Upvotes: 1

Views: 1858

Answers (1)

Roham
Roham

Reputation: 2110

In async version of WS you should also convert your database access to async because it is usually works in sync mode (I mean the database queries). So you should change it by method decorators or other ways that mentioned here.

One way to solve this problem is to have a method and a decorator like:

from channels.db import database_sync_to_async

@database_sync_to_async  # a method that goes in your TestConsumer class
def update_key_query(self):
    key_query = some_obj
    key_query.active_connections = 2
    key_query.save()

and then use it when you need it like following:

async def websocket_connect(self, event):
        ...
        await self.update_key_query()
        ...

Upvotes: 4

Related Questions