Python AsyncJsonWebSocketConsumer 问题

标签 python asynchronous websocket synchronization consumer

我收到这个错误

您不能从异步上下文中调用它 - 使用线程或sync_to_async。 当我运行我的项目时。我的消费者看起来像

class AllConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.user_id = str(self.scope['url_route']['kwargs']['user_id'])
        await self.accept()
        user = sync_to_async(User.objects.get(id=self.user_id))
        sync_to_async(OnlineUserActivity.update_user_activity(user))

        online_users = []
        user_activity_objects = OnlineUserActivity.get_user_activities(timedelta(minutes=1))
        for online_user in user_activity_objects:
            online_users.append(online_user.user_id)
        all_users = User.objects.all().values_list('id')
        for _user in all_users:
            await self.channel_layer.group_send(
                str(_user[0]),
                {
                    "type": "online_users",
                    'message': online_users
                }
            )

        await self.channel_layer.group_add(
            self.user_id,
            self.channel_name,
        )

    async def disconnect(self, close_code):
        try:
            online_user = OnlineUserActivity.objects.get(user_id=self.user_id)
            online_user.delete()
            online_users = []

            user_activity_objects = OnlineUserActivity.get_user_activities(timedelta(minutes=1))
            for x in user_activity_objects:
                online_users.append(x.user_id)
            all_users = User.objects.all().values_list('id')
            for _user in all_users:
                await self.channel_layer.group_send(
                    str(_user[0]),
                    {
                        "type": "online_users",
                        'message': online_users
                    }
                )
        except Exception as e:
            print(e)
        async_to_sync(self.channel_layer.group_discard(
            self.user_id,
            self.channel_name
        ))

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        socket_type = text_data_json['type']
        bla bla. ... 

我的路由 py 看起来像

from django.urls import re_path

from core import consumers

websocket_urlpatterns = [
    re_path(r'ws/(?P<user_id>\w+)/$', consumers.AllConsumer),
]

我的 websockets 请求触及我的消费者,没关系,但它会抛出这样的异常。 我的操作系统是Ubuntu 18 一切正常,无需同步到异步部分,你能帮助我吗,谢谢 主要问题,错误问题是

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

最佳答案

而不是:

user = sync_to_async(User.objects.get(id=self.user_id))

您应该使用:

user = await sync_to_async(User.objects.get)(id=self.user_id)

关于Python AsyncJsonWebSocketConsumer 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59304466/

相关文章:

ios - IOS 上的 Safari 中每个域允许多少个同时 websocket 连接?

Python Pandas : Convert a date string to milliseconds since epoch and back to date string?

python - flask-assets - sass 不解析@import scss 指令中的相对路径

python删除dtype和数组末尾并获取列表列表

python - 为什么 numpy.float16 会破坏 OpenBlas/Atlas 功能?

C# async/await 进度报告不符合预期顺序

tomcat - 受防火墙保护的 ActiveMQ 服务器的 WS 代理

sockets - Ember 2,验收测试,Websocket挂起,然后Then()等待挂起

javascript - 异步 javascript - 如何传递参数?

javascript - 监听JS中的事件