async.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. ====================
  2. Asynchronous support
  3. ====================
  4. .. currentmodule:: asgiref.sync
  5. Django has support for writing asynchronous ("async") views, along with an
  6. entirely async-enabled request stack if you are running under
  7. :doc:`ASGI </howto/deployment/asgi/index>`. Async views will still work under
  8. WSGI, but with performance penalties, and without the ability to have efficient
  9. long-running requests.
  10. We're still working on async support for the ORM and other parts of Django.
  11. You can expect to see this in future releases. For now, you can use the
  12. :func:`sync_to_async` adapter to interact with the sync parts of Django.
  13. There is also a whole range of async-native Python libraries that you can
  14. integrate with.
  15. Async views
  16. ===========
  17. Any view can be declared async by making the callable part of it return a
  18. coroutine - commonly, this is done using ``async def``. For a function-based
  19. view, this means declaring the whole view using ``async def``. For a
  20. class-based view, this means declaring the HTTP method handlers, such as
  21. ``get()`` and ``post()`` as ``async def`` (not its ``__init__()``, or
  22. ``as_view()``).
  23. .. note::
  24. Django uses ``asyncio.iscoroutinefunction`` to test if your view is
  25. asynchronous or not. If you implement your own method of returning a
  26. coroutine, ensure you set the ``_is_coroutine`` attribute of the view
  27. to ``asyncio.coroutines._is_coroutine`` so this function returns ``True``.
  28. Under a WSGI server, async views will run in their own, one-off event loop.
  29. This means you can use async features, like concurrent async HTTP requests,
  30. without any issues, but you will not get the benefits of an async stack.
  31. The main benefits are the ability to service hundreds of connections without
  32. using Python threads. This allows you to use slow streaming, long-polling, and
  33. other exciting response types.
  34. If you want to use these, you will need to deploy Django using
  35. :doc:`ASGI </howto/deployment/asgi/index>` instead.
  36. .. warning::
  37. You will only get the benefits of a fully-asynchronous request stack if you
  38. have *no synchronous middleware* loaded into your site. If there is a piece
  39. of synchronous middleware, then Django must use a thread per request to
  40. safely emulate a synchronous environment for it.
  41. Middleware can be built to support :ref:`both sync and async
  42. <async-middleware>` contexts. Some of Django's middleware is built like
  43. this, but not all. To see what middleware Django has to adapt for, you can
  44. turn on debug logging for the ``django.request`` logger and look for log
  45. messages about *"Asynchronous handler adapted for middleware ..."*.
  46. In both ASGI and WSGI mode, you can still safely use asynchronous support to
  47. run code concurrently rather than serially. This is especially handy when
  48. dealing with external APIs or data stores.
  49. If you want to call a part of Django that is still synchronous, like the ORM,
  50. you will need to wrap it in a :func:`sync_to_async` call. For example::
  51. from asgiref.sync import sync_to_async
  52. results = await sync_to_async(Blog.objects.get, thread_sensitive=True)(pk=123)
  53. You may find it easier to move any ORM code into its own function and call that
  54. entire function using :func:`sync_to_async`. For example::
  55. from asgiref.sync import sync_to_async
  56. def _get_blog(pk):
  57. return Blog.objects.select_related('author').get(pk=pk)
  58. get_blog = sync_to_async(_get_blog, thread_sensitive=True)
  59. If you accidentally try to call a part of Django that is still synchronous-only
  60. from an async view, you will trigger Django's
  61. :ref:`asynchronous safety protection <async-safety>` to protect your data from
  62. corruption.
  63. Performance
  64. -----------
  65. When running in a mode that does not match the view (e.g. an async view under
  66. WSGI, or a traditional sync view under ASGI), Django must emulate the other
  67. call style to allow your code to run. This context-switch causes a small
  68. performance penalty of around a millisecond.
  69. This is also true of middleware. Django will attempt to minimize the number of
  70. context-switches between sync and async. If you have an ASGI server, but all
  71. your middleware and views are synchronous, it will switch just once, before it
  72. enters the middleware stack.
  73. However, if you put synchronous middleware between an ASGI server and an
  74. asynchronous view, it will have to switch into sync mode for the middleware and
  75. then back to async mode for the view. Django will also hold the sync thread
  76. open for middleware exception propagation. This may not be noticeable at first,
  77. but adding this penalty of one thread per request can remove any async
  78. performance advantage.
  79. You should do your own performance testing to see what effect ASGI versus WSGI
  80. has on your code. In some cases, there may be a performance increase even for
  81. a purely synchronous codebase under ASGI because the request-handling code is
  82. still all running asynchronously. In general you will only want to enable ASGI
  83. mode if you have asynchronous code in your project.
  84. .. _async-safety:
  85. Async safety
  86. ============
  87. .. envvar:: DJANGO_ALLOW_ASYNC_UNSAFE
  88. Certain key parts of Django are not able to operate safely in an async
  89. environment, as they have global state that is not coroutine-aware. These parts
  90. of Django are classified as "async-unsafe", and are protected from execution in
  91. an async environment. The ORM is the main example, but there are other parts
  92. that are also protected in this way.
  93. If you try to run any of these parts from a thread where there is a *running
  94. event loop*, you will get a
  95. :exc:`~django.core.exceptions.SynchronousOnlyOperation` error. Note that you
  96. don't have to be inside an async function directly to have this error occur. If
  97. you have called a sync function directly from an async function,
  98. without using :func:`sync_to_async` or similar, then it can also occur. This is
  99. because your code is still running in a thread with an active event loop, even
  100. though it may not be declared as async code.
  101. If you encounter this error, you should fix your code to not call the offending
  102. code from an async context. Instead, write your code that talks to async-unsafe
  103. functions in its own, sync function, and call that using
  104. :func:`asgiref.sync.sync_to_async` (or any other way of running sync code in
  105. its own thread).
  106. The async context can be imposed upon you by the environment in which you are
  107. running your Django code. For example, Jupyter_ notebooks and IPython_
  108. interactive shells both transparently provide an active event loop so that it is
  109. easier to interact with asynchronous APIs.
  110. If you're using an IPython shell, you can disable this event loop by running::
  111. %autoawait off
  112. as a command at the IPython prompt. This will allow you to run synchronous code
  113. without generating :exc:`~django.core.exceptions.SynchronousOnlyOperation`
  114. errors; however, you also won't be able to ``await`` asynchronous APIs. To turn
  115. the event loop back on, run::
  116. %autoawait on
  117. If you're in an environment other than IPython (or you can't turn off
  118. ``autoawait`` in IPython for some reason), you are *certain* there is no chance
  119. of your code being run concurrently, and you *absolutely* need to run your sync
  120. code from an async context, then you can disable the warning by setting the
  121. :envvar:`DJANGO_ALLOW_ASYNC_UNSAFE` environment variable to any value.
  122. .. warning::
  123. If you enable this option and there is concurrent access to the
  124. async-unsafe parts of Django, you may suffer data loss or corruption. Be
  125. very careful and do not use this in production environments.
  126. If you need to do this from within Python, do that with ``os.environ``::
  127. import os
  128. os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
  129. .. _Jupyter: https://jupyter.org/
  130. .. _IPython: https://ipython.org
  131. Async adapter functions
  132. =======================
  133. It is necessary to adapt the calling style when calling sync code from an async
  134. context, or vice-versa. For this there are two adapter functions, from the
  135. ``asgiref.sync`` module: :func:`async_to_sync` and :func:`sync_to_async`. They
  136. are used to transition between the calling styles while preserving
  137. compatibility.
  138. These adapter functions are widely used in Django. The `asgiref`_ package
  139. itself is part of the Django project, and it is automatically installed as a
  140. dependency when you install Django with ``pip``.
  141. .. _asgiref: https://pypi.org/project/asgiref/
  142. ``async_to_sync()``
  143. -------------------
  144. .. function:: async_to_sync(async_function, force_new_loop=False)
  145. Takes an async function and returns a sync function that wraps it. Can be used
  146. as either a direct wrapper or a decorator::
  147. from asgiref.sync import async_to_sync
  148. async def get_data(...):
  149. ...
  150. sync_get_data = async_to_sync(get_data)
  151. @async_to_sync
  152. async def get_other_data(...):
  153. ...
  154. The async function is run in the event loop for the current thread, if one is
  155. present. If there is no current event loop, a new event loop is spun up
  156. specifically for the single async invocation and shut down again once it
  157. completes. In either situation, the async function will execute on a different
  158. thread to the calling code.
  159. Threadlocals and contextvars values are preserved across the boundary in both
  160. directions.
  161. :func:`async_to_sync` is essentially a more powerful version of the
  162. :py:func:`asyncio.run` function in Python's standard library. As well
  163. as ensuring threadlocals work, it also enables the ``thread_sensitive`` mode of
  164. :func:`sync_to_async` when that wrapper is used below it.
  165. ``sync_to_async()``
  166. -------------------
  167. .. function:: sync_to_async(sync_function, thread_sensitive=True)
  168. Takes a sync function and returns an async function that wraps it. Can be used
  169. as either a direct wrapper or a decorator::
  170. from asgiref.sync import sync_to_async
  171. async_function = sync_to_async(sync_function, thread_sensitive=False)
  172. async_function = sync_to_async(sensitive_sync_function, thread_sensitive=True)
  173. @sync_to_async
  174. def sync_function(...):
  175. ...
  176. Threadlocals and contextvars values are preserved across the boundary in both
  177. directions.
  178. Sync functions tend to be written assuming they all run in the main
  179. thread, so :func:`sync_to_async` has two threading modes:
  180. * ``thread_sensitive=True`` (the default): the sync function will run in the
  181. same thread as all other ``thread_sensitive`` functions. This will be the
  182. main thread, if the main thread is synchronous and you are using the
  183. :func:`async_to_sync` wrapper.
  184. * ``thread_sensitive=False``: the sync function will run in a brand new thread
  185. which is then closed once the invocation completes.
  186. .. warning::
  187. ``asgiref`` version 3.3.0 changed the default value of the
  188. ``thread_sensitive`` parameter to ``True``. This is a safer default, and in
  189. many cases interacting with Django the correct value, but be sure to
  190. evaluate uses of ``sync_to_async()`` if updating ``asgiref`` from a prior
  191. version.
  192. Thread-sensitive mode is quite special, and does a lot of work to run all
  193. functions in the same thread. Note, though, that it *relies on usage of*
  194. :func:`async_to_sync` *above it in the stack* to correctly run things on the
  195. main thread. If you use ``asyncio.run()`` or similar, it will fall back to
  196. running thread-sensitive functions in a single, shared thread, but this will
  197. not be the main thread.
  198. The reason this is needed in Django is that many libraries, specifically
  199. database adapters, require that they are accessed in the same thread that they
  200. were created in. Also a lot of existing Django code assumes it all runs in the
  201. same thread, e.g. middleware adding things to a request for later use in views.
  202. Rather than introduce potential compatibility issues with this code, we instead
  203. opted to add this mode so that all existing Django sync code runs in the same
  204. thread and thus is fully compatible with async mode. Note that sync code will
  205. always be in a *different* thread to any async code that is calling it, so you
  206. should avoid passing raw database handles or other thread-sensitive references
  207. around.