Я хочу сделать простую программу на каналах django - я открываю Websocket, а затем слушаю, как пользователи нажимают кнопку или нажимают любую клавишу. Если такое событие происходит, JS отправляет сообщение в каналы, где он получает доступ к базе данных, где есть модель счетчика, увеличивая его в зависимости от нажатия или клавиши, а затем отправляет его обратно в группу по слоям. К сожалению, возникает ошибка. Почему вызывается ошибка контекста, если я уже использовал database_sync_to_async?

Мой consumers.py:

from channels.generic.websocket import AsyncWebsocketConsumer
import json
from channels.db import database_sync_to_async
from .models import Licznik
    
    class MyConsumer(AsyncWebsocketConsumer):
        async def connect(self):
            self.room_group_name = 'main_room'
            self.counter = await database_sync_to_async(self.get_counter)()
    
            await (self.channel_layer.group_add)(
                self.room_group_name,
                self.channel_name
            )
            await self.accept()
    
    
       def get_counter(self):
           return Licznik.objects.all()[0]
    
       async def receive(self, text_data):
            if text_data == "klik":
                self.counter.klik +=1
            elif text_data == "klak":
                self.counter.key += 1
            await database_sync_to_async(self.counter.save()) #error here
            klik = self.counter.klik
            klak = self.counter.key
            await (self.channel_layer.group_send)(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'klik': klik,
                    'klak': klak
                }
            )
    
       async def chat_message(self, event):
            message_klik = event['klik']
            message_klak = event['klak']
            await self.send(text_data=json.dumps({
                'klik': message_klik,
                'klak': message_klak
            }))
    
       async def disconnect(self, close_code):
            await (self.channel_layer.group_discard)(
                self.room_group_name,
                self.channel_name
            )
            await self.close()

Ошибка:

Exception inside application: You cannot call this from an async context - use a thread or sync_to_async.
Traceback (most recent call last):
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/sessions.py", line 183, in __call__
    return await self.inner(receive, self.send)
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/middleware.py", line 41, in coroutine_call
    await inner_instance(receive, send)
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/consumer.py", line 58, in __call__
    await await_many_dispatch(
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/utils.py", line 51, in await_many_dispatch
    await dispatch(result)
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/consumer.py", line 73, in dispatch
    await handler(message)
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/channels/generic/websocket.py", line 196, in websocket_receive
    await self.receive(text_data=message["text"])
  File "/Users/dottore/PycharmProjects/klikator/klikator/klikacz/consumers.py", line 26, in receive
    await database_sync_to_async(self.counter.save())
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save
    self.save_base(using=using, force_insert=force_insert,
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base
    updated = self._save_table(
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/base.py", line 872, in _save_table
    updated = self._do_update(base_qs, using, pk_val, values, update_fields,
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/base.py", line 926, in _do_update
    return filtered._update(values) > 0
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/query.py", line 803, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1522, in execute_sql
    cursor = super().execute_sql(result_type)
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1154, in execute_sql
    cursor = self.connection.cursor()
  File "/Users/dottore/PycharmProjects/klikator/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 24, in inner
    raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
1
DevVile 3 Ноя 2020 в 02:04

1 ответ

Лучший ответ

Вы должны вызывать метод database_sync_to_async, а не метод сохранения напрямую. :

async def receive(self, text_data):
        ...
        await database_sync_to_async(self.counter.save)()
        ...
1
drec4s 2 Ноя 2020 в 23:32