async.txt 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. ====================
  2. Asynchronous support
  3. ====================
  4. .. versionadded:: 3.0
  5. Django has developing support for asynchronous ("async") Python, but does not
  6. yet support asynchronous views or middleware; they will be coming in a future
  7. release.
  8. There is limited support for other parts of the async ecosystem; namely, Django
  9. can natively talk :doc:`ASGI </howto/deployment/asgi/index>`, and some async
  10. safety support.
  11. .. _async-safety:
  12. Async-safety
  13. ------------
  14. Certain key parts of Django are not able to operate safely in an asynchronous
  15. environment, as they have global state that is not coroutine-aware. These parts
  16. of Django are classified as "async-unsafe", and are protected from execution in
  17. an asynchronous environment. The ORM is the main example, but there are other
  18. parts that are also protected in this way.
  19. If you try to run any of these parts from a thread where there is a *running
  20. event loop*, you will get a
  21. :exc:`~django.core.exceptions.SynchronousOnlyOperation` error. Note that you
  22. don't have to be inside an async function directly to have this error occur. If
  23. you have called a synchronous function directly from an asynchronous function
  24. without going through something like ``sync_to_async`` or a threadpool, then it
  25. can also occur, as your code is still running in an asynchronous context.
  26. If you encounter this error, you should fix your code to not call the offending
  27. code from an async context; instead, write your code that talks to async-unsafe
  28. in its own, synchronous function, and call that using
  29. ``asgiref.sync.async_to_sync``, or any other preferred way of running
  30. synchronous code in its own thread.
  31. If you are *absolutely* in dire need to run this code from an asynchronous
  32. context - for example, it is being forced on you by an external environment,
  33. and you are sure there is no chance of it being run concurrently (e.g. you are
  34. in a Jupyter_ notebook), then you can disable the warning with the
  35. ``DJANGO_ALLOW_ASYNC_UNSAFE`` environment variable.
  36. .. warning::
  37. If you enable this option and there is concurrent access to the
  38. async-unsafe parts of Django, you may suffer data loss or corruption. Be
  39. very careful and do not use this in production environments.
  40. If you need to do this from within Python, do that with ``os.environ``::
  41. os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
  42. .. _Jupyter: https://jupyter.org/