Moving from Django-WSGI to ASGI/Uvicorn: issue with AppConfig.ready() being called synchronously in asynchronous context

I'm moving my application views to asynchronous calls as they are requesting a number of data from the database.

When running the async views from the wsgi server, everything is working according to expectations.

But to be able to really benefit from the async rewriting of my application, I'm now trying to start my application as a asgi application, together with Uvicorn.

asgi.py:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyAppName.settings')
application = get_asgi_application()

While launching the asgi server through:

uvicorn MyAppName.asgi:application

I end up triggering:

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

The reason is that through my AppConfig.ready() method, I'm calling a function which populates some key data from database in cache.

my_app/apps.py:

class MyAppConfig(AppConfig):
    name = 'my_app'

    def ready(self):
        """
        hook for application initialization : 
        is called as soon as the registry is fully populated for this app
        put your startup code here
        useful to run some code inside the Django appserver process
        or you need to initialize something in memory, in the context of the Django app server
        """
        # Reinitializing cache to enable the cached_dicts to get the right values:
        cached_dicts.set_up_cache_dicts()

AppConfig.ready() is by design a sync method in Django, but the asgi server apparently requires those database requests to be async

I have tested different things to prevent the Exception, or to declare AppConfig.ready() as an async method. At best, There is no exception, but the caching function is not awaited and the cache is not populated.

There seems to be no way to call async code through AppConfig.ready().

Any idea how I could populate my cache from database during the launch of my Django application in an asgi context ?

Вернуться на верх