简体   繁体   English

将数据从 Django Channels 消费者保存到数据库

[英]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:我很难编辑来自 Django 频道使用者的数据库条目,这是涉及的一段代码:

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?也许使用@database_sync_to_async? Any advice is appreciated!任何建议表示赞赏!

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).在 WS 的异步版本中,您还应该将数据库访问转换为异步,因为它通常在同步模式下工作(我的意思是数据库查询)。 So you should change it by method decorators or other ways that mentionedhere .所以你应该通过方法装饰器或这里提到的其他方式来改变它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM