【问题标题】:Getting a use a thread or sync_to_async error获取使用线程或 sync_to_async 错误
【发布时间】:2023-01-27 20:33:07
【问题描述】:

所以我正在处理 Django 网络聊天。我只是切换了我的数据库结构以支持群聊。到目前为止,我更改了代码,我正在努力弄清楚如何修复以下错误。

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

这是我来自 consumers.py 的 websocket_connect

    async def websocket_connect(self, event):
        print('connected', event)
        user = self.scope['user']
        print(user.online)
        threads = Thread.objects.filter(participant__user=user).prefetch_related()
        for thread in threads:
            chat_room = f'user_chatroom_{thread.id}'
            self.chat_room = chat_room
            await self.channel_layer.group_add(
                chat_room,
                self.channel_name
            )
        await self.send({
            'type': 'websocket.accept'
        })

我为每一个答案感到高兴!

我试图更改线程变量,但我无法更改它,因为我需要它。

【问题讨论】:

    标签: python django asynchronous websocket async-await


    【解决方案1】:

    现在(暂时)修复它。它可能不是最好的解决方案,但这对我有帮助。

    import os
    
    os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
    

    希望我能提供帮助,如果有更好的解决方案,请纠正我。

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多