django3 raise SynchronousOnlyOperation in jupyter

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)
 in 
      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 SynchronousOnlyOperation in jupyter)