美文网首页《Django By Example》
django3 raise SynchronousOnlyOpe

django3 raise SynchronousOnlyOpe

作者: swotpp | 来源:发表于2020-04-07 20:48 被阅读0次

Django setup

import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rest.settings')
django.setup()

from call import models
models.Call.objects.all()

raise SynchronousOnlyOperation after run:

SynchronousOnlyOperation                  Traceback (most recent call last)
<ipython-input-19-28f5a54bd77c> in <module>
      1 content = ContentType.objects.filter(
----> 2     app_label='call', model='Expertfk').first()
......
~/venv/traffic/lib/python3.7/site-packages/django/utils/asyncio.py in inner(*args, **kwargs)
     22                 else:
     23                     if event_loop.is_running():
---> 24                         raise SynchronousOnlyOperation(message)
     25             # Pass onwards.
     26             return func(*args, **kwargs)

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

Need add DJANGO_ALLOW_ASYNC_UNSAFE

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

import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rest.settings')
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
django.setup()

from call import models
from django.contrib.contenttypes.models import ContentType

models.Call.objects.all()

Then it will be ok.

Reference:

  1. How to use django 3.0 ORM in a Jupyter Notebook without triggering the async context check?

  2. Async-safety

相关文章

网友评论

    本文标题:django3 raise SynchronousOnlyOpe

    本文链接:https://www.haomeiwen.com/subject/neyophtx.html