异步支持

New in Django 3.0.

Django has support for writing asynchronous (“async”) views, along with an entirely async-enabled request stack if you are running under ASGI. Async views will still work under WSGI, but with performance penalties, and without the ability to have efficient long-running requests.

We’re still working on async support for the ORM and other parts of Django. You can expect to see this in future releases. For now, you can use the sync_to_async() adapter to interact with the sync parts of Django. There is also a whole range of async-native Python libraries that you can integrate with.

Changed in Django 3.1:

Support for async views was added.

Async views

New in Django 3.1.

Any view can be declared async by making the callable part of it return a coroutine - commonly, this is done using async def. For a function-based view, this means declaring the whole view using async def. For a class-based view, this means making its __call__() method an async def (not its __init__() or as_view()).

注解

Django uses asyncio.iscoroutinefunction to test if your view is asynchronous or not. If you implement your own method of returning a coroutine, ensure you set the _is_coroutine attribute of the view to asyncio.coroutines._is_coroutine so this function returns True.

Under a WSGI server, async views will run in their own, one-off event loop. This means you can use async features, like concurrent async HTTP requests, without any issues, but you will not get the benefits of an async stack.

The main benefits are the ability to service hundreds of connections without using Python threads. This allows you to use slow streaming, long-polling, and other exciting response types.

If you want to use these, you will need to deploy Django using ASGI instead.

警告

You will only get the benefits of a fully-asynchronous request stack if you have no synchronous middleware loaded into your site. If there is a piece of synchronous middleware, then Django must use a thread per request to safely emulate a synchronous environment for it.

Middleware can be built to support both sync and async contexts. Some of Django’s middleware is built like this, but not all. To see what middleware Django has to adapt, you can turn on debug logging for the django.request logger and look for log messages about “Synchronous middleware … adapted”.

In both ASGI and WSGI mode, you can still safely use asynchronous support to run code concurrently rather than serially. This is especially handy when dealing with external APIs or data stores.

If you want to call a part of Django that is still synchronous, like the ORM, you will need to wrap it in a sync_to_async() call. For example:

  1. from asgiref.sync import sync_to_async
  2. results = sync_to_async(Blog.objects.get)(pk=123)

You may find it easier to move any ORM code into its own function and call that entire function using sync_to_async(). For example:

  1. from asgiref.sync import sync_to_async
  2. @sync_to_async
  3. def get_blog(pk):
  4. return Blog.objects.select_related('author').get(pk=pk)

If you accidentally try to call a part of Django that is still synchronous-only from an async view, you will trigger Django’s asynchronous safety protection to protect your data from corruption.

性能

When running in a mode that does not match the view (e.g. an async view under WSGI, or a traditional sync view under ASGI), Django must emulate the other call style to allow your code to run. This context-switch causes a small performance penalty of around a millisecond.

This is also true of middleware. Django will attempt to minimize the number of context-switches between sync and async. If you have an ASGI server, but all your middleware and views are synchronous, it will switch just once, before it enters the middleware stack.

However, if you put synchronous middleware between an ASGI server and an asynchronous view, it will have to switch into sync mode for the middleware and then back to async mode for the view. Django will also hold the sync thread open for middleware exception propagation. This may not be noticeable at first, but adding this penalty of one thread per request can remove any async performance advantage.

You should do your own performance testing to see what effect ASGI versus WSGI has on your code. In some cases, there may be a performance increase even for a purely synchronous codebase under ASGI because the request-handling code is still all running asynchronously. In general you will only want to enable ASGI mode if you have asynchronous code in your project.

Async safety

DJANGO_ALLOW_ASYNC_UNSAFE

Certain key parts of Django are not able to operate safely in an async environment, as they have global state that is not coroutine-aware. These parts of Django are classified as “async-unsafe”, and are protected from execution in an async environment. The ORM is the main example, but there are other parts that are also protected in this way.

If you try to run any of these parts from a thread where there is a running event loop, you will get a SynchronousOnlyOperation error. Note that you don’t have to be inside an async function directly to have this error occur. If you have called a sync function directly from an async function, without using sync_to_async() or similar, then it can also occur. This is because your code is still running in a thread with an active event loop, even though it may not be declared as async code.

If you encounter this error, you should fix your code to not call the offending code from an async context. Instead, write your code that talks to async-unsafe functions in its own, sync function, and call that using asgiref.sync.sync_to_async() (or any other way of running sync code in its own thread).

You may still be forced to run sync code from an async context. For example, if the requirement is forced on you by an external environment, such as in a Jupyter notebook. If you are sure there is no chance of the code being run concurrently, and you absolutely need to run this sync code from an async context, then you can disable the warning by setting the DJANGO_ALLOW_ASYNC_UNSAFE environment variable to any value.

警告

如果启用了这个选项,并且同时访问 Django 的异步不安全 (async-unsafe) 部分,你会遇到数据丢失或损坏,所以一定要非常小心,并且不要再生产环境里这样使用。

如果你需要在 Python 中执行此操作,请使用 os.environ

  1. import os
  2. os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"

异步适配函数

It is necessary to adapt the calling style when calling sync code from an async context, or vice-versa. For this there are two adapter functions, from the asgiref.sync module: async_to_sync() and sync_to_async(). They are used to transition between the calling styles while preserving compatibility.

这些适配函数广泛应用于 Django。asgiref 包本身就是 Django 项目的部分,并且它在当你用 pip 方式安装 Django 时,会作为依赖项目自动安装。

async_to_sync()

async_to_sync(async_function, force_new_loop=False)

Takes an async function and returns a sync function that wraps it. Can be used as either a direct wrapper or a decorator:

  1. from asgiref.sync import async_to_sync
  2. async def get_data(...):
  3. ...
  4. sync_get_data = async_to_sync(get_data)
  5. @async_to_sync
  6. async def get_other_data(...):
  7. ...

The async function is run in the event loop for the current thread, if one is present. If there is no current event loop, a new event loop is spun up specifically for the single async invocation and shut down again once it completes. In either situation, the async function will execute on a different thread to the calling code.

Threadlocals 和 contextvars 值在两个方向的边界上都保持不变。

async_to_sync() is essentially a more powerful version of the asyncio.run() function in Python’s standard library. As well as ensuring threadlocals work, it also enables the thread_sensitive mode of sync_to_async() when that wrapper is used below it.

sync_to_async()

sync_to_async(sync_function, thread_sensitive=False)

Takes a sync function and returns an async function that wraps it. Can be used as either a direct wrapper or a decorator:

  1. from asgiref.sync import sync_to_async
  2. async_function = sync_to_async(sync_function)
  3. async_function = sync_to_async(sensitive_sync_function, thread_sensitive=True)
  4. @sync_to_async
  5. def sync_function(...):
  6. ...

Threadlocals 和 contextvars 值在两个方向的边界上都保持不变。

Sync functions tend to be written assuming they all run in the main thread, so sync_to_async() has two threading modes:

  • thread_sensitive=False (the default): the sync function will run in a brand new thread which is then closed once the invocation completes.
  • thread_sensitive=True: the sync function will run in the same thread as all other thread_sensitive functions. This will be the main thread, if the main thread is synchronous and you are using the async_to_sync() wrapper.

Thread-sensitive mode is quite special, and does a lot of work to run all functions in the same thread. Note, though, that it relies on usage of async_to_sync() above it in the stack to correctly run things on the main thread. If you use asyncio.run() or similar, it will fall back to running thread-sensitive functions in a single, shared thread, but this will not be the main thread.

The reason this is needed in Django is that many libraries, specifically database adapters, require that they are accessed in the same thread that they were created in. Also a lot of existing Django code assumes it all runs in the same thread, e.g. middleware adding things to a request for later use in views.

Rather than introduce potential compatibility issues with this code, we instead opted to add this mode so that all existing Django sync code runs in the same thread and thus is fully compatible with async mode. Note that sync code will always be in a different thread to any async code that is calling it, so you should avoid passing raw database handles or other thread-sensitive references around.