You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: docs/topics/databases.rst
+22-1
Original file line number
Diff line number
Diff line change
@@ -11,7 +11,8 @@ code is already run in a synchronous mode and Channels will do the cleanup
11
11
for you as part of the ``SyncConsumer`` code.
12
12
13
13
If you are writing asynchronous code, however, you will need to call
14
-
database methods in a safe, synchronous context, using ``database_sync_to_async``.
14
+
database methods in a safe, synchronous context, using ``database_sync_to_async``
15
+
or by using the asynchronous methods prefixed with ``a`` like ``Model.objects.aget()``.
15
16
16
17
17
18
Database Connections
@@ -26,6 +27,11 @@ Python 3.7 and below, and `min(32, os.cpu_count() + 4)` for Python 3.8+.
26
27
27
28
To avoid having too many threads idling in connections, you can instead rewrite your code to use async consumers and only dip into threads when you need to use Django's ORM (using ``database_sync_to_async``).
28
29
30
+
When using async consumers Channels will automatically call Django's ``close_old_connections`` method when a new connection is started, when a connection is closed, and whenever anything is received from the client.
31
+
This mirrors Django's logic for closing old connections at the start and end of a request, to the extent possible. Connections are *not* automatically closed when sending data from a consumer since Channels has no way
32
+
to determine if this is a one-off send (and connections could be closed) or a series of sends (in which closing connections would kill performance). Instead, if you have a long-lived async consumer you should
33
+
periodically call ``aclose_old_connections`` (see below).
34
+
29
35
30
36
database_sync_to_async
31
37
----------------------
@@ -58,3 +64,18 @@ You can also use it as a decorator:
58
64
@database_sync_to_async
59
65
defget_name(self):
60
66
return User.objects.all()[0].name
67
+
68
+
aclose_old_connections
69
+
----------------------
70
+
71
+
``django.db.aclose_old_connections`` is an async wrapper around Django's
72
+
``close_old_connections``. When using a long-lived ``AsyncConsumer`` that
73
+
calls the Django ORM it is important to call this function periodically.
74
+
75
+
Preferrably, this function should be called before making the first query
76
+
in a while. For example, it should be called if the Consumer is woken up
77
+
by a channels layer event and needs to make a few ORM queries to determine
78
+
what to send to the client. This function should be called *before* making
79
+
those queries. Calling this function more than necessary is not necessarily
80
+
a bad thing, but it does require a context switch to synchronous code and
0 commit comments