Debian Codegraph @

docs/howto/django.rst

raw
1 Integrate with Django
2 =====================
3
4 If you're looking at adding real-time capabilities to a Django project with
5 WebSocket, you have two main options.
6
7 1. Using Django Channels_, a project adding WebSocket to Django, among other
8 features. This approach is fully supported by Django. However, it requires
9 switching to a new deployment architecture.
10
11 2. Deploying a separate WebSocket server next to your Django project. This
12 technique is well suited when you need to add a small set of real-time
13 features — maybe a notification service — to an HTTP application.
14
15 .. _Channels: https://channels.readthedocs.io/
16
17 This guide shows how to implement the second technique with websockets. It
18 assumes familiarity with Django.
19
20 Authenticate connections
21 ------------------------
22
23 Since the websockets server runs outside of Django, we need to integrate it
24 with ``django.contrib.auth``.
25
26 We will generate authentication tokens in the Django project. Then we will
27 send them to the websockets server, where they will authenticate the user.
28
29 Generating a token for the current user and making it available in the browser
30 is up to you. You could render the token in a template or fetch it with an API
31 call.
32
33 Refer to the topic guide on :doc:`authentication <../topics/authentication>`
34 for details on this design.
35
36 Generate tokens
37 ...............
38
39 We want secure, short-lived tokens containing the user ID. We'll rely on
40 `django-sesame`_, a small library designed exactly for this purpose.
41
42 .. _django-sesame: https://github.com/aaugustin/django-sesame
43
44 Add django-sesame to the dependencies of your Django project, install it, and
45 configure it in the settings of the project:
46
47 .. code-block:: python
48
49 AUTHENTICATION_BACKENDS = [
50 "django.contrib.auth.backends.ModelBackend",
51 "sesame.backends.ModelBackend",
52 ]
53
54 (If your project already uses another authentication backend than the default
55 ``"django.contrib.auth.backends.ModelBackend"``, adjust accordingly.)
56
57 You don't need ``"sesame.middleware.AuthenticationMiddleware"``. It is for
58 authenticating users in the Django server, while we're authenticating them in
59 the websockets server.
60
61 We'd like our tokens to be valid for 30 seconds. We expect web pages to load
62 and to establish the WebSocket connection within this delay. Configure
63 django-sesame accordingly in the settings of your Django project:
64
65 .. code-block:: python
66
67 SESAME_MAX_AGE = 30
68
69 If you expect your web site to load faster for all clients, a shorter lifespan
70 is possible. However, in the context of this document, it would make manual
71 testing more difficult.
72
73 You could also enable single-use tokens. However, this would update the last
74 login date of the user every time a WebSocket connection is established. This
75 doesn't seem like a good idea, both in terms of behavior and in terms of
76 performance.
77
78 Now you can generate tokens in a ``django-admin shell`` as follows:
79
80 .. code-block:: pycon
81
82 >>> from django.contrib.auth import get_user_model
83 >>> User = get_user_model()
84 >>> user = User.objects.get(username="<your username>")
85 >>> from sesame.utils import get_token
86 >>> get_token(user)
87 '<your token>'
88
89 Keep this console open: since tokens expire after 30 seconds, you'll have to
90 generate a new token every time you want to test connecting to the server.
91
92 Validate tokens
93 ...............
94
95 Let's move on to the websockets server.
96
97 Add websockets to the dependencies of your Django project and install it.
98 Indeed, we're going to reuse the environment of the Django project, so we can
99 call its APIs in the websockets server.
100
101 Now here's how to implement authentication.
102
103 .. literalinclude:: ../../example/django/authentication.py
104 :caption: authentication.py
105
106 Let's unpack this code.
107
108 We're calling ``django.setup()`` before doing anything with Django because
109 we're using Django in a `standalone script`_. This assumes that the
110 ``DJANGO_SETTINGS_MODULE`` environment variable is set to the Python path to
111 your settings module.
112
113 .. _standalone script: https://docs.djangoproject.com/en/stable/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage
114
115 The connection handler reads the first message received from the client, which
116 is expected to contain a django-sesame token. Then it authenticates the user
117 with :func:`~sesame.utils.get_user`, the API provided by django-sesame for
118 `authentication outside a view`_.
119
120 .. _authentication outside a view: https://django-sesame.readthedocs.io/en/stable/howto.html#outside-a-view
121
122 If authentication fails, it closes the connection and exits.
123
124 When we call an API that makes a database query such as
125 :func:`~sesame.utils.get_user`, we wrap the call in :func:`~asyncio.to_thread`.
126 Indeed, the Django ORM doesn't support asynchronous I/O. It would block the
127 event loop if it didn't run in a separate thread.
128
129 Finally, we start a server with :func:`~websockets.asyncio.server.serve`.
130
131 We're ready to test!
132
133 Download :download:`authentication.py <../../example/django/authentication.py>`,
134 make sure the ``DJANGO_SETTINGS_MODULE`` environment variable is set properly,
135 and start the websockets server:
136
137 .. code-block:: console
138
139 $ python authentication.py
140
141 Generate a new token — remember, they're only valid for 30 seconds — and use
142 it to connect to your server. Paste your token and press Enter when you get a
143 prompt:
144
145 .. code-block:: console
146
147 $ websockets ws://localhost:8888/
148 Connected to ws://localhost:8888/
149 > <your token>
150 < Hello <your username>!
151 Connection closed: 1000 (OK).
152
153 It works!
154
155 If you enter an expired or invalid token, authentication fails and the server
156 closes the connection:
157
158 .. code-block:: console
159
160 $ websockets ws://localhost:8888/
161 Connected to ws://localhost:8888.
162 > not a token
163 Connection closed: 1011 (internal error) authentication failed.
164
165 You can also test from a browser by generating a new token and running the
166 following code in the JavaScript console of the browser:
167
168 .. code-block:: javascript
169
170 websocket = new WebSocket("ws://localhost:8888/");
171 websocket.onopen = (event) => websocket.send("<your token>");
172 websocket.onmessage = (event) => console.log(event.data);
173
174 If you don't want to import your entire Django project into the websockets
175 server, you can create a simpler Django project with ``django.contrib.auth``,
176 ``django-sesame``, a suitable ``User`` model, and a subset of the settings of
177 the main project.
178
179 Stream events
180 -------------
181
182 We can connect and authenticate but our server doesn't do anything useful yet!
183
184 Let's send a message every time a user makes an action in the admin. This
185 message will be broadcast to all users who can access the model on which the
186 action was made. This may be used for showing notifications to other users.
187
188 Many use cases for WebSocket with Django follow a similar pattern.
189
190 Set up event stream
191 ...................
192
193 We need an event stream to enable communications between Django and websockets.
194 Both sides connect permanently to the stream. Then Django writes events and
195 websockets reads them. For the sake of simplicity, we'll rely on `Redis
196 Pub/Sub`_.
197
198 .. _Redis Pub/Sub: https://redis.io/topics/pubsub
199
200 The easiest way to add Redis to a Django project is by configuring a cache
201 backend with `django-redis`_. This library manages connections to Redis
202 efficiently, persisting them between requests, and provides an API to access
203 the Redis connection directly.
204
205 .. _django-redis: https://github.com/jazzband/django-redis
206
207 Install Redis, add django-redis to the dependencies of your Django project,
208 install it, and configure it in the settings of the project:
209
210 .. code-block:: python
211
212 CACHES = {
213 "default": {
214 "BACKEND": "django_redis.cache.RedisCache",
215 "LOCATION": "redis://127.0.0.1:6379/1",
216 },
217 }
218
219 If you already have a default cache, add a new one with a different name and
220 change ``get_redis_connection("default")`` in the code below to the same name.
221
222 Publish events
223 ..............
224
225 Now let's write events to the stream.
226
227 Add the following code to a module that is imported when your Django project
228 starts. Typically, you would put it in a :download:`signals.py
229 <../../example/django/signals.py>` module, which you would import in the
230 ``AppConfig.ready()`` method of one of your apps:
231
232 .. literalinclude:: ../../example/django/signals.py
233 :caption: signals.py
234
235 This code runs every time the admin saves a ``LogEntry`` object to keep track
236 of a change. It extracts interesting data, serializes it to JSON, and writes
237 an event to Redis.
238
239 Let's check that it works:
240
241 .. code-block:: console
242
243 $ redis-cli
244 127.0.0.1:6379> SELECT 1
245 OK
246 127.0.0.1:6379[1]> SUBSCRIBE events
247 Reading messages... (press Ctrl-C to quit)
248 1) "subscribe"
249 2) "events"
250 3) (integer) 1
251
252 Leave this command running, start the Django development server and make
253 changes in the admin: add, modify, or delete objects. You should see
254 corresponding events published to the ``"events"`` stream.
255
256 Broadcast events
257 ................
258
259 Now let's turn to reading events and broadcasting them to connected clients.
260 We need to add several features:
261
262 * Keep track of connected clients so we can broadcast messages.
263 * Tell which content types the user has permission to view or to change.
264 * Connect to the message stream and read events.
265 * Broadcast these events to users who have corresponding permissions.
266
267 Here's a complete implementation.
268
269 .. literalinclude:: ../../example/django/notifications.py
270 :caption: notifications.py
271
272 Since the ``get_content_types()`` function makes a database query, it is
273 wrapped inside :func:`asyncio.to_thread()`. It runs once when each WebSocket
274 connection is open; then its result is cached for the lifetime of the
275 connection. Indeed, running it for each message would trigger database queries
276 for all connected users at the same time, which would hurt the database.
277
278 The connection handler merely registers the connection in a global variable,
279 associated to the list of content types for which events should be sent to
280 that connection, and waits until the client disconnects.
281
282 The ``process_events()`` function reads events from Redis and broadcasts them to
283 all connections that should receive them. We don't care much if a sending a
284 notification fails. This happens when a connection drops between the moment we
285 iterate on connections and the moment the corresponding message is sent.
286
287 Since Redis can publish a message to multiple subscribers, multiple instances
288 of this server can safely run in parallel.
289
290 Does it scale?
291 --------------
292
293 In theory, given enough servers, this design can scale to a hundred million
294 clients, since Redis can handle ten thousand servers and each server can
295 handle ten thousand clients. In practice, you would need a more scalable
296 message stream before reaching that scale, due to the volume of messages.