Запуск Celery в контексте asyncio
Я запускаю приложение Django, которое использует Channels и Celery. У меня возникла недетерминированная проблема, когда иногда мои задачи Celery запускаются из цикла событий asyncio.
Я получаю следующие ошибки:
[2021-12-08 20:02:23,699: ERROR/MainProcess] Signal handler <function switch_schema at 0x7f1ce3c09d30> raised: SynchronousOnlyOperation('You cannot call this from an async context - use a thread or sync_to_async.')
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/celery/utils/dispatch/signal.py", line 276, in send
response = receiver(signal=self, sender=sender, **named)
File "/usr/local/lib/python3.8/site-packages/tenant_schemas_celery/app.py", line 48, in switch_schema
tenant = task.get_tenant_for_schema(schema_name=schema)
File "/usr/local/lib/python3.8/site-packages/tenant_schemas_celery/task.py", line 43, in get_tenant_for_schema
cached_value = get_tenant_model().objects.get(schema_name=schema_name)
File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 431, in get
num = len(clone)
File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 262, in __len__
self._fetch_all()
File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql
cursor = self.connection.cursor()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 31, in inner
raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
Это происходит не всегда и не всегда бросается на одной и той же строке.
Кто-нибудь знает, почему это происходит и как это предотвратить?