django.core.exceptions.SynchronousOnlyOperation 您无法从异步上下文中调用它 - 使用线程或sync_to_async

问题描述 投票:0回答:1

我正在使用 Django 通道来实现 Web 套接字 我想在consumers.py中使用ORM来获取数据库查询

看我的代码

导入json 从channels.generic.websocket导入AsyncWebsocketConsumer 从.models导入游戏 从 account.models 导入 CustomUser 作为用户 从channels.db导入database_sync_to_async

`类 CameraStreamConsumer(AsyncWebsocketConsumer):

def __init__(self, *args, **kwargs):
    print("initializing")
    self.counter = 0
    super().__init__(*args, **kwargs)

async def connect(self):
    await self.accept()
    print("accepted connection")

async def disconnect(self, close_code):
    pass
    print("disconect connection")
async def receive(self, text_data=None,):
    print(" iam getting data online")
    data = json.loads(text_data)
    

    if data.get('type') == 'started':

        await self.handle_game_started(data)
    

async def get_game(self, game_id):
    game_obj = await database_sync_to_async(Game.objects.get)(id=game_id)
    return game_obj

async def get_user(self, user_id):
    user_obj = await database_sync_to_async(User.objects.get)(id=user_id)
    return user_obj

async def handle_game_started(self, data):
    game_id = data.get('game_id')
    user_id = data.get('user_id')
    game_obj = await self.get_game(game_id)
    user_obj = await self.get_user(user_id)
    if game_obj and user_obj:
        game_creator = game_obj.creator
        if game_creator == user_obj:
            print("user is creator")
            await self.send(text_data=json.dumps({'message': f'Game {game_id} Started'}))

`

我收到错误

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

我也尝试与

from asgiref.sync import sync_to_async 
但还是一样

python django websocket django-channels
1个回答
0
投票

你可以试试这个

@database_sync_to_async
def get_user(self, user_id):
    return User.objects.filter(id=user_id).last()

async def handle_game_started(self, data):
    user_id = data.get('user_id')
    user_obj = await self.get_user(user_id)
    print(user_obj, "userobjects")
© www.soinside.com 2019 - 2024. All rights reserved.