async.txt 11 KB

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