Calling Django ORM queries from within an async function running in an event loop

Viewed 790

[Setup] I am using Django 3.0 as a wsgi application.

I need to run the coroutine (shown below) from a view. This runs within an asyncio eventloop. From this event loop/coroutine I need to fetch some objects in the database using Django's ORM but django throws the following exception:

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

import asyncio
import concurrent

def get_users_from_db():
    return User.objects.all()

async def do_some_async_stuff():
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
    loop = asyncio.get_event_loop()
    attachments = await loop.run_in_executor(executor, get_users_from_db)

def view(request):
    task = LOOP.create_task(do_some_async_stuff)
    result = not LOOP.is_running() and LOOP.run_until_complete(task)

I am not sure what I am doing wrong. As far as I understand Django's doc suggests I should be able to run synchronous tasks (like an ORM query) in a separate thread, but that still doesn't work.

The interesting thing is, running the code locally using manage.py runserver works fine, however running it with `gunicorn --bind 127.0.0.1:8000 src.config.wsgi:application throws the above exception.

0 Answers
Related