| 1 |
==================== |
| 2 |
Asynchronous support |
| 3 |
==================== |
| 4 |
|
| 5 |
.. currentmodule:: asgiref.sync |
| 6 |
|
| 7 |
Django has support for writing asynchronous ("async") views, along with an |
| 8 |
entirely async-enabled request stack if you are running under |
| 9 |
:doc:`ASGI </howto/deployment/asgi/index>`. Async views will still work under |
| 10 |
WSGI, but with performance penalties, and without the ability to have efficient |
| 11 |
long-running requests. |
| 12 |
|
| 13 |
We're still working on async support for the ORM and other parts of Django. |
| 14 |
You can expect to see this in future releases. For now, you can use the |
| 15 |
:func:`sync_to_async` adapter to interact with the sync parts of Django. |
| 16 |
There is also a whole range of async-native Python libraries that you can |
| 17 |
integrate with. |
| 18 |
|
| 19 |
Async views |
| 20 |
=========== |
| 21 |
|
| 22 |
Any view can be declared async by making the callable part of it return a |
| 23 |
coroutine - commonly, this is done using ``async def``. For a function-based |
| 24 |
view, this means declaring the whole view using ``async def``. For a |
| 25 |
class-based view, this means declaring the HTTP method handlers, such as |
| 26 |
``get()`` and ``post()`` as ``async def`` (not its ``__init__()``, or |
| 27 |
``as_view()``). |
| 28 |
|
| 29 |
.. note:: |
| 30 |
|
| 31 |
Django uses ``asgiref.sync.iscoroutinefunction`` to test if your view is |
| 32 |
asynchronous or not. If you implement your own method of returning a |
| 33 |
coroutine, ensure you use ``asgiref.sync.markcoroutinefunction`` so this |
| 34 |
function returns ``True``. |
| 35 |
|
| 36 |
Under a WSGI server, async views will run in their own, one-off event loop. |
| 37 |
This means you can use async features, like concurrent async HTTP requests, |
| 38 |
without any issues, but you will not get the benefits of an async stack. |
| 39 |
|
| 40 |
The main benefits are the ability to service hundreds of connections without |
| 41 |
using Python threads. This allows you to use slow streaming, long-polling, and |
| 42 |
other exciting response types. |
| 43 |
|
| 44 |
If you want to use these, you will need to deploy Django using |
| 45 |
:doc:`ASGI </howto/deployment/asgi/index>` instead. |
| 46 |
|
| 47 |
.. warning:: |
| 48 |
|
| 49 |
You will only get the benefits of a fully-asynchronous request stack if you |
| 50 |
have *no synchronous middleware* loaded into your site. If there is a piece |
| 51 |
of synchronous middleware, then Django must use a thread per request to |
| 52 |
safely emulate a synchronous environment for it. |
| 53 |
|
| 54 |
Middleware can be built to support :ref:`both sync and async |
| 55 |
<async-middleware>` contexts. Some of Django's middleware is built like |
| 56 |
this, but not all. To see what middleware Django has to adapt for, you can |
| 57 |
turn on debug logging for the ``django.request`` logger and look for log |
| 58 |
messages about *"Asynchronous handler adapted for middleware ..."*. |
| 59 |
|
| 60 |
In both ASGI and WSGI mode, you can still safely use asynchronous support to |
| 61 |
run code concurrently rather than serially. This is especially handy when |
| 62 |
dealing with external APIs or data stores. |
| 63 |
|
| 64 |
If you want to call a part of Django that is still synchronous, you will need |
| 65 |
to wrap it in a :func:`sync_to_async` call. For example:: |
| 66 |
|
| 67 |
from asgiref.sync import sync_to_async |
| 68 |
|
| 69 |
results = await sync_to_async(sync_function, thread_sensitive=True)(pk=123) |
| 70 |
|
| 71 |
If you accidentally try to call a part of Django that is synchronous-only |
| 72 |
from an async view, you will trigger Django's |
| 73 |
:ref:`asynchronous safety protection <async-safety>` to protect your data from |
| 74 |
corruption. |
| 75 |
|
| 76 |
Decorators |
| 77 |
---------- |
| 78 |
|
| 79 |
The following decorators can be used with both synchronous and asynchronous |
| 80 |
view functions: |
| 81 |
|
| 82 |
* :func:`~django.views.decorators.cache.cache_control` |
| 83 |
* :func:`~django.views.decorators.cache.never_cache` |
| 84 |
* :func:`~django.views.decorators.common.no_append_slash` |
| 85 |
* :func:`~django.views.decorators.csrf.csrf_exempt` |
| 86 |
* :func:`~django.views.decorators.csrf.csrf_protect` |
| 87 |
* :func:`~django.views.decorators.csrf.ensure_csrf_cookie` |
| 88 |
* :func:`~django.views.decorators.csrf.requires_csrf_token` |
| 89 |
* :func:`~django.views.decorators.debug.sensitive_variables` |
| 90 |
* :func:`~django.views.decorators.debug.sensitive_post_parameters` |
| 91 |
* :func:`~django.views.decorators.gzip.gzip_page` |
| 92 |
* :func:`~django.views.decorators.http.condition` |
| 93 |
* ``conditional_page()`` |
| 94 |
* :func:`~django.views.decorators.http.etag` |
| 95 |
* :func:`~django.views.decorators.http.last_modified` |
| 96 |
* :func:`~django.views.decorators.http.require_http_methods` |
| 97 |
* :func:`~django.views.decorators.http.require_GET` |
| 98 |
* :func:`~django.views.decorators.http.require_POST` |
| 99 |
* :func:`~django.views.decorators.http.require_safe` |
| 100 |
* :func:`~django.views.decorators.vary.vary_on_cookie` |
| 101 |
* :func:`~django.views.decorators.vary.vary_on_headers` |
| 102 |
* ``xframe_options_deny()`` |
| 103 |
* ``xframe_options_sameorigin()`` |
| 104 |
* ``xframe_options_exempt()`` |
| 105 |
|
| 106 |
For example:: |
| 107 |
|
| 108 |
from django.views.decorators.cache import never_cache |
| 109 |
|
| 110 |
|
| 111 |
@never_cache |
| 112 |
def my_sync_view(request): ... |
| 113 |
|
| 114 |
|
| 115 |
@never_cache |
| 116 |
async def my_async_view(request): ... |
| 117 |
|
| 118 |
Queries & the ORM |
| 119 |
----------------- |
| 120 |
|
| 121 |
With some exceptions, Django can run ORM queries asynchronously as well:: |
| 122 |
|
| 123 |
async for author in Author.objects.filter(name__startswith="A"): |
| 124 |
book = await author.books.afirst() |
| 125 |
|
| 126 |
Detailed notes can be found in :ref:`async-queries`, but in short: |
| 127 |
|
| 128 |
* All ``QuerySet`` methods that cause an SQL query to occur have an |
| 129 |
``a``-prefixed asynchronous variant. |
| 130 |
|
| 131 |
* ``async for`` is supported on all QuerySets (including the output of |
| 132 |
``values()`` and ``values_list()``.) |
| 133 |
|
| 134 |
Django also supports some asynchronous model methods that use the database:: |
| 135 |
|
| 136 |
async def make_book(*args, **kwargs): |
| 137 |
book = Book(...) |
| 138 |
await book.asave(using="secondary") |
| 139 |
|
| 140 |
|
| 141 |
async def make_book_with_tags(tags, *args, **kwargs): |
| 142 |
book = await Book.objects.acreate(...) |
| 143 |
await book.tags.aset(tags) |
| 144 |
|
| 145 |
Transactions do not yet work in async mode. If you have a piece of code that |
| 146 |
needs transactions behavior, we recommend you write that piece as a single |
| 147 |
synchronous function and call it using :func:`sync_to_async`. |
| 148 |
|
| 149 |
:ref:`Persistent database connections <persistent-database-connections>`, set |
| 150 |
via the :setting:`CONN_MAX_AGE` setting, should also be disabled in async mode. |
| 151 |
Instead, use your database backend's built-in connection pooling if available, |
| 152 |
or investigate a third-party connection pooling option if required. |
| 153 |
|
| 154 |
.. _async_performance: |
| 155 |
|
| 156 |
Performance |
| 157 |
----------- |
| 158 |
|
| 159 |
When running in a mode that does not match the view (e.g. an async view under |
| 160 |
WSGI, or a traditional sync view under ASGI), Django must emulate the other |
| 161 |
call style to allow your code to run. This context-switch causes a small |
| 162 |
performance penalty of around a millisecond. |
| 163 |
|
| 164 |
This is also true of middleware. Django will attempt to minimize the number of |
| 165 |
context-switches between sync and async. If you have an ASGI server, but all |
| 166 |
your middleware and views are synchronous, it will switch just once, before it |
| 167 |
enters the middleware stack. |
| 168 |
|
| 169 |
However, if you put synchronous middleware between an ASGI server and an |
| 170 |
asynchronous view, it will have to switch into sync mode for the middleware and |
| 171 |
then back to async mode for the view. Django will also hold the sync thread |
| 172 |
open for middleware exception propagation. This may not be noticeable at first, |
| 173 |
but adding this penalty of one thread per request can remove any async |
| 174 |
performance advantage. |
| 175 |
|
| 176 |
You should do your own performance testing to see what effect ASGI versus WSGI |
| 177 |
has on your code. In some cases, there may be a performance increase even for |
| 178 |
a purely synchronous codebase under ASGI because the request-handling code is |
| 179 |
still all running asynchronously. In general you will only want to enable ASGI |
| 180 |
mode if you have asynchronous code in your project. |
| 181 |
|
| 182 |
.. _async-handling-disconnect: |
| 183 |
|
| 184 |
Handling disconnects |
| 185 |
-------------------- |
| 186 |
|
| 187 |
For long-lived requests, a client may disconnect before the view returns a |
| 188 |
response. In this case, an ``asyncio.CancelledError`` will be raised in the |
| 189 |
view. You can catch this error and handle it if you need to perform any |
| 190 |
cleanup:: |
| 191 |
|
| 192 |
async def my_view(request): |
| 193 |
try: |
| 194 |
# Do some work |
| 195 |
... |
| 196 |
except asyncio.CancelledError: |
| 197 |
# Handle disconnect |
| 198 |
raise |
| 199 |
|
| 200 |
You can also :ref:`handle client disconnects in streaming responses |
| 201 |
<request-response-streaming-disconnect>`. |
| 202 |
|
| 203 |
.. _async-safety: |
| 204 |
|
| 205 |
Async safety |
| 206 |
============ |
| 207 |
|
| 208 |
.. envvar:: DJANGO_ALLOW_ASYNC_UNSAFE |
| 209 |
|
| 210 |
Certain key parts of Django are not able to operate safely in an async |
| 211 |
environment, as they have global state that is not coroutine-aware. These parts |
| 212 |
of Django are classified as "async-unsafe", and are protected from execution in |
| 213 |
an async environment. The ORM is the main example, but there are other parts |
| 214 |
that are also protected in this way. |
| 215 |
|
| 216 |
If you try to run any of these parts from a thread where there is a *running |
| 217 |
event loop*, you will get a |
| 218 |
:exc:`~django.core.exceptions.SynchronousOnlyOperation` error. Note that you |
| 219 |
don't have to be inside an async function directly to have this error occur. If |
| 220 |
you have called a sync function directly from an async function, |
| 221 |
without using :func:`sync_to_async` or similar, then it can also occur. This is |
| 222 |
because your code is still running in a thread with an active event loop, even |
| 223 |
though it may not be declared as async code. |
| 224 |
|
| 225 |
If you encounter this error, you should fix your code to not call the offending |
| 226 |
code from an async context. Instead, write your code that talks to async-unsafe |
| 227 |
functions in its own, sync function, and call that using |
| 228 |
:func:`asgiref.sync.sync_to_async` (or any other way of running sync code in |
| 229 |
its own thread). |
| 230 |
|
| 231 |
The async context can be imposed upon you by the environment in which you are |
| 232 |
running your Django code. For example, Jupyter_ notebooks and IPython_ |
| 233 |
interactive shells both transparently provide an active event loop so that it is |
| 234 |
easier to interact with asynchronous APIs. |
| 235 |
|
| 236 |
If you're using an IPython shell, you can disable this event loop by running: |
| 237 |
|
| 238 |
.. code-block:: shell |
| 239 |
|
| 240 |
%autoawait off |
| 241 |
|
| 242 |
as a command at the IPython prompt. This will allow you to run synchronous code |
| 243 |
without generating :exc:`~django.core.exceptions.SynchronousOnlyOperation` |
| 244 |
errors; however, you also won't be able to ``await`` asynchronous APIs. To turn |
| 245 |
the event loop back on, run: |
| 246 |
|
| 247 |
.. code-block:: shell |
| 248 |
|
| 249 |
%autoawait on |
| 250 |
|
| 251 |
If you're in an environment other than IPython (or you can't turn off |
| 252 |
``autoawait`` in IPython for some reason), you are *certain* there is no chance |
| 253 |
of your code being run concurrently, and you *absolutely* need to run your sync |
| 254 |
code from an async context, then you can disable the warning by setting the |
| 255 |
:envvar:`DJANGO_ALLOW_ASYNC_UNSAFE` environment variable to any value. |
| 256 |
|
| 257 |
.. warning:: |
| 258 |
|
| 259 |
If you enable this option and there is concurrent access to the |
| 260 |
async-unsafe parts of Django, you may suffer data loss or corruption. Be |
| 261 |
very careful and do not use this in production environments. |
| 262 |
|
| 263 |
If you need to do this from within Python, do that with ``os.environ``:: |
| 264 |
|
| 265 |
import os |
| 266 |
|
| 267 |
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" |
| 268 |
|
| 269 |
.. _Jupyter: https://jupyter.org/ |
| 270 |
.. _IPython: https://ipython.org |
| 271 |
|
| 272 |
Async adapter functions |
| 273 |
======================= |
| 274 |
|
| 275 |
It is necessary to adapt the calling style when calling sync code from an async |
| 276 |
context, or vice-versa. For this there are two adapter functions, from the |
| 277 |
``asgiref.sync`` module: :func:`async_to_sync` and :func:`sync_to_async`. They |
| 278 |
are used to transition between the calling styles while preserving |
| 279 |
compatibility. |
| 280 |
|
| 281 |
These adapter functions are widely used in Django. The :pypi:`asgiref` package |
| 282 |
itself is part of the Django project, and it is automatically installed as a |
| 283 |
dependency when you install Django with ``pip``. |
| 284 |
|
| 285 |
``async_to_sync()`` |
| 286 |
------------------- |
| 287 |
|
| 288 |
.. function:: async_to_sync(async_function, force_new_loop=False) |
| 289 |
|
| 290 |
Takes an async function and returns a sync function that wraps it. Can be used |
| 291 |
as either a direct wrapper or a decorator:: |
| 292 |
|
| 293 |
from asgiref.sync import async_to_sync |
| 294 |
|
| 295 |
|
| 296 |
async def get_data(): ... |
| 297 |
|
| 298 |
|
| 299 |
sync_get_data = async_to_sync(get_data) |
| 300 |
|
| 301 |
|
| 302 |
@async_to_sync |
| 303 |
async def get_other_data(): ... |
| 304 |
|
| 305 |
The async function is run in the event loop for the current thread, if one is |
| 306 |
present. If there is no current event loop, a new event loop is spun up |
| 307 |
specifically for the single async invocation and shut down again once it |
| 308 |
completes. In either situation, the async function will execute on a different |
| 309 |
thread to the calling code. |
| 310 |
|
| 311 |
Threadlocals and contextvars values are preserved across the boundary in both |
| 312 |
directions. |
| 313 |
|
| 314 |
:func:`async_to_sync` is essentially a more powerful version of the |
| 315 |
:py:func:`asyncio.run` function in Python's standard library. As well |
| 316 |
as ensuring threadlocals work, it also enables the ``thread_sensitive`` mode of |
| 317 |
:func:`sync_to_async` when that wrapper is used below it. |
| 318 |
|
| 319 |
``sync_to_async()`` |
| 320 |
------------------- |
| 321 |
|
| 322 |
.. function:: sync_to_async(sync_function, thread_sensitive=True) |
| 323 |
|
| 324 |
Takes a sync function and returns an async function that wraps it. Can be used |
| 325 |
as either a direct wrapper or a decorator:: |
| 326 |
|
| 327 |
from asgiref.sync import sync_to_async |
| 328 |
|
| 329 |
async_function = sync_to_async(sync_function, thread_sensitive=False) |
| 330 |
async_function = sync_to_async(sensitive_sync_function, thread_sensitive=True) |
| 331 |
|
| 332 |
|
| 333 |
@sync_to_async |
| 334 |
def sync_function(): ... |
| 335 |
|
| 336 |
Threadlocals and contextvars values are preserved across the boundary in both |
| 337 |
directions. |
| 338 |
|
| 339 |
Sync functions tend to be written assuming they all run in the main |
| 340 |
thread, so :func:`sync_to_async` has two threading modes: |
| 341 |
|
| 342 |
* ``thread_sensitive=True`` (the default): the sync function will run in the |
| 343 |
same thread as all other ``thread_sensitive`` functions. This will be the |
| 344 |
main thread, if the main thread is synchronous and you are using the |
| 345 |
:func:`async_to_sync` wrapper. |
| 346 |
|
| 347 |
* ``thread_sensitive=False``: the sync function will run in a brand new thread |
| 348 |
which is then closed once the invocation completes. |
| 349 |
|
| 350 |
.. warning:: |
| 351 |
|
| 352 |
``asgiref`` version 3.3.0 changed the default value of the |
| 353 |
``thread_sensitive`` parameter to ``True``. This is a safer default, and in |
| 354 |
many cases interacting with Django the correct value, but be sure to |
| 355 |
evaluate uses of ``sync_to_async()`` if updating ``asgiref`` from a prior |
| 356 |
version. |
| 357 |
|
| 358 |
Thread-sensitive mode is quite special, and does a lot of work to run all |
| 359 |
functions in the same thread. Note, though, that it *relies on usage of* |
| 360 |
:func:`async_to_sync` *above it in the stack* to correctly run things on the |
| 361 |
main thread. If you use ``asyncio.run()`` or similar, it will fall back to |
| 362 |
running thread-sensitive functions in a single, shared thread, but this will |
| 363 |
not be the main thread. |
| 364 |
|
| 365 |
The reason this is needed in Django is that many libraries, specifically |
| 366 |
database adapters, require that they are accessed in the same thread that they |
| 367 |
were created in. Also a lot of existing Django code assumes it all runs in the |
| 368 |
same thread, e.g. middleware adding things to a request for later use in views. |
| 369 |
|
| 370 |
Rather than introduce potential compatibility issues with this code, we instead |
| 371 |
opted to add this mode so that all existing Django sync code runs in the same |
| 372 |
thread and thus is fully compatible with async mode. Note that sync code will |
| 373 |
always be in a *different* thread to any async code that is calling it, so you |
| 374 |
should avoid passing raw database handles or other thread-sensitive references |
| 375 |
around. |
| 376 |
|
| 377 |
In practice this restriction means that you should not pass features of the |
| 378 |
database ``connection`` object when calling ``sync_to_async()``. Doing so will |
| 379 |
trigger the thread safety checks: |
| 380 |
|
| 381 |
.. code-block:: pycon |
| 382 |
|
| 383 |
# DJANGO_SETTINGS_MODULE=settings.py python -m asyncio |
| 384 |
>>> import asyncio |
| 385 |
>>> from asgiref.sync import sync_to_async |
| 386 |
>>> from django.db import connection |
| 387 |
>>> # In an async context so you cannot use the database directly: |
| 388 |
>>> connection.cursor() |
| 389 |
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from |
| 390 |
an async context - use a thread or sync_to_async. |
| 391 |
>>> # Nor can you pass resolved connection attributes across threads: |
| 392 |
>>> await sync_to_async(connection.cursor)() |
| 393 |
django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread |
| 394 |
can only be used in that same thread. The object with alias 'default' was |
| 395 |
created in thread id 4371465600 and this is thread id 6131478528. |
| 396 |
|
| 397 |
Rather, you should encapsulate all database access within a helper function |
| 398 |
that can be called with ``sync_to_async()`` without relying on the connection |
| 399 |
object in the calling code. |