summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorCarlton Gibson <carlton.gibson@noumenal.es>2022-04-20 11:56:11 +0200
committerCarlton Gibson <carlton.gibson@noumenal.es>2022-04-20 14:52:52 +0200
commit86324f37b3ce0b1fb3973c10f2e1e4655b5680cd (patch)
tree1d16070d56f3371ce42eb36d17467d92fa6de586 /docs
parent7ac2cd638f9b674408ca8fc5bd467ecea18ad51f (diff)
[4.0.x] Refs #33646 -- Added example for async cross-thread connection access.
Backport of 6b53114dd862ec97c282fdfdc83579cbd6d1560d from main
Diffstat (limited to 'docs')
-rw-r--r--docs/topics/async.txt26
1 files changed, 26 insertions, 0 deletions
diff --git a/docs/topics/async.txt b/docs/topics/async.txt
index 1cc5a7c15c..acafa5374d 100644
--- a/docs/topics/async.txt
+++ b/docs/topics/async.txt
@@ -278,3 +278,29 @@ 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.
+
+In practice this restriction means that you should not pass features of the
+database ``connection`` object when calling ``sync_to_async()``. Doing so will
+trigger the thread safety checks:
+
+.. code-block:: pycon
+
+ # DJANGO_SETTINGS_MODULE=settings.py python -m asyncio
+ >>> import asyncio
+ >>> from asgiref.sync import sync_to_async
+ >>> from django.db import connection
+ >>> # In an async context so you cannot use the database directly:
+ >>> connection.cursor()
+ ...
+ django.core.exceptions.SynchronousOnlyOperation: You cannot call this from
+ an async context - use a thread or sync_to_async.
+ >>> # Nor can you pass resolved connection attributes across threads:
+ >>> await sync_to_async(connection.cursor)()
+ ...
+ django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread
+ can only be used in that same thread. The object with alias 'default' was
+ created in thread id 4371465600 and this is thread id 6131478528.
+
+Rather, you should encapsulate all database access within a helper function
+that can be called with ``sync_to_async()`` without relying on the connection
+object in the calling code.