1

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!

1 Answer 1

4

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()
        ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.