README.md 15.6 KB
Newer Older
Andi's avatar
Andi committed
1 2 3 4 5 6 7 8 9 10
# Django Channels Workshop

Source / Guide: <https://channels.readthedocs.io/en/stable/tutorial/index.html>

## Short Intro

* We will build a simple chat app with two pages:
  * An index view that lets you type the name of a chat room to join
  * A room view that lets you see messages posted in a particular chat room
* Room view will use a **WebSocket** to communicate with the Django server and listen for any messages that are posted
Andreas Straßer's avatar
Andreas Straßer committed
11
* The workshop will take about 90 minutes
Andi's avatar
Andi committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

## Installation and basic setup

### Installation

* Start PyCharm and create new Project "django-channels-workshop"
* Open Terminal and install requirements:

  ```
  $ pip install django==3.2 channels==3.0.2
  ```
* See if channels was installed correctly:

  ```
  $ python -c "import channels; print(channels.__version__)"
  3.0.2
  ```

### Creating a project and an app

* Start a new Django project:
  ```
  $ django-admin startproject mysite
  ```
* Clean up folder structure:
  * move `manage.py` one level up
  * move everything in `mysite/mysite/` one level up
  * delete `mysite/mysite/` folder (it should be empty)
* Start a django app:
  ```
  $ python manage.py startapp chat
  ```
* Don't be intimidated by the huge number of files, we will only use a bunch of them:
  * `mysite/settings.py`
  * `chat/views.py`
  * ... we will also create a few new ones
* Add the chat app to the installed apps in `mysite/settings.py`:

  ```
  INSTALLED_APPS = [
      'chat',
      ...
  ]
  ```

### Add an index view

* Create the directory `templates/` within the `chat/` dir
* Create the directory `chat/` within the `chat/templates/` dir
* Create a file called `index.html` inside `chat/templates/chat/`
* Put the following code inside:

  ```
  <!-- chat/templates/chat/index.html -->
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <title>Chat Rooms</title>
  </head>
  <body>
      What chat room would you like to enter?<br>
      <input id="room-name-input" type="text" size="100"><br>
      <input id="room-name-submit" type="button" value="Enter">
  
      <script>
          document.querySelector('#room-name-input').focus();
          document.querySelector('#room-name-input').onkeyup = function(e) {
              if (e.keyCode === 13) {  // enter, return
                  document.querySelector('#room-name-submit').click();
              }
          };
  
          document.querySelector('#room-name-submit').onclick = function(e) {
              let roomName = document.querySelector('#room-name-input').value;
              window.location.pathname = '/chat/' + roomName + '/';
          };
      </script>
  </body>
  </html>
  ```
* Create a view function for the index view. Open `chat/views.py` and write:

  ```
  # chat/views.py
  from django.shortcuts import render
  
  
  def index(request):
      return render(request, 'chat/index.html')
  ```
* We still need to map the view to a URL in order to be able to see the page. Create the file `chat/urls.py` and write:

  ```
  # chat/urls.py
  from django.urls import path
  
  from . import views
  
  urlpatterns = [
      path('', views.index, name='index'),
  ]
  ```
* Now we need to tell Django to look for the `chat/urls.py` file. To do that open `mysite/urls.py` and adjust it to have:

  ```
  # mysite/urls.py
  from django.conf.urls import include
  from django.urls import path
  from django.contrib import admin
  
  urlpatterns = [
      path('chat/', include('chat.urls')),
      path('admin/', admin.site.urls),
  ]
  ```
* Run the server for the first time:

  ```
  $ python manage.py runserver
  ```
* Navigate to <http://127.0.0.1:8000/chat/>, you should now see the `index.html`
  * Try entering a name for a chat room, e.g. 'lobby' and hitting "Enter"
  * You should see a "Page not found (404)" Error, as we have not defined the room view yet!
* Stop the server in the terminal by pressing Ctrl+C
* **RECAP: What happens, when a client wants to access the** `chat/` **URL?**
  * Django starts looking for the `ROOT_URLCONF` in `mysite/settings.py`. It is `'mysite.urls'`
  * Inside `mysite/urls.py` the `'chat/'` path is defined in the `urlpatterns`. It includes the `chat.urls`.
  * Inside `chat/urls.py` an empty path (i.e. nothing behind the after `http://127.0.0.1:8000/chat/`) points to the `views.index` function
  * The `index` function inside `chat/views.py` simply renders the `chat/templates/chat/index.html` file (the path inside the `render(...)` function is relative to the `templates/` dir)
* So far we have not used Django Channels at all, so let's start doing so now!

### Integrate the Channels library

* Instead of the Python WSGI (Web Server Gateway Interface, can only handle HTTP requests) we need to tell Django to use ASGI (Asynchronous Server Gateway Interface, can also handle WebSockets and other)
* To do that open the `mysite/settings.py` file and do the following:
  * Add `channels` to the installed apps:

    ```
    INSTALLED_APPS = [
        'chat',
        'channels',
        ...
    ]
    ```
  * Tell Django where to find the ASGI application (and remove WSGI):

    ```
    # WSGI_APPLICATION = 'mysite.wsgi.application'
    ASGI_APPLICATION = 'mysite.asgi.application'
    ```
* Adjust the `mysite/asgi.py` file to contain the following:

  ```
  # mysite/asgi.py
  import os
  
  from channels.routing import ProtocolTypeRouter
  from django.core.asgi import get_asgi_application
  
  os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
  
  application = ProtocolTypeRouter({
      "http": get_asgi_application(),
      # "websocket": ... (we will add that later)
  })
  ```
* Let's restart the server using `$ python manage.py runserver` and once again navigate to <http://127.0.0.1:8000/chat/>
* You should still be able to see the index view and creating a room should still result in a 404 Error.

**(10 Minutes Break)**

## Implement a Chat Server

Quick Recap: We have a simple index view, where a chat room name can be entered, but those chat rooms do not exist yet (404).

Now let's get the view for the chat rooms going!

### Add the room view

* Create the file `chat/templates/chat/room.html`, open it and type the following:

  ```
  <!-- chat/templates/chat/room.html -->
  <!DOCTYPE html>
  <html>
  <head>
      <meta charset="utf-8"/>
      <title>Chat Room</title>
  </head>
  <body>
      <textarea id="chat-log" cols="100" rows="20" readonly></textarea><br>
      <input id="chat-message-input" type="text" size="100"><br>
      <input id="chat-message-submit" type="button" value="Send">
      {{ room_name|json_script:"room-name" }}
Andreas Straßer's avatar
Andreas Straßer committed
207 208
      <!-- <script id="room-name" type="application/json">"<<the actual room_name>>"</script> -->
      
Andi's avatar
Andi committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
      <script>
          const roomName = JSON.parse(document.getElementById('room-name').textContent);
  
          const chatSocket = new WebSocket(
              'ws://'
              + window.location.host
              + '/ws/chat/'
              + roomName
              + '/'
          );
  
          chatSocket.onmessage = function(event) {
              const data = JSON.parse(event.data);
              document.querySelector('#chat-log').value += (data.message + '\n');
          };
  
          chatSocket.onclose = function(event) {
              console.error('Chat socket closed unexpectedly');
          };
  
          document.querySelector('#chat-message-input').focus();
          document.querySelector('#chat-message-input').onkeyup = function(e) {
              if (e.keyCode === 13) {  // enter, return
                  document.querySelector('#chat-message-submit').click();
              }
          };
  
          document.querySelector('#chat-message-submit').onclick = function(e) {
              const messageInput = document.querySelector('#chat-message-input');
              const message = messageInput.value;
              chatSocket.send(JSON.stringify({
                  'message': message
              }));
              messageInput.value = '';
          };
      </script>
  </body>
  </html>
  ```
* Open `chat/views.py` and add the room view below the index view:

  ```
  def room(request, room_name):
      return render(request, 'chat/room.html', {
          'room_name': room_name
      })
  ```
* Define a URL for it in the `chat/urls.py`:

  ```
  urlpatterns = [
      path('', views.index, name='index'),
      path('<str:room_name>/', views.room, name='room'),
  ]
  ```
* Let's restart the server using `$ python manage.py runserver` and once again navigate to <http://127.0.0.1:8000/chat/>
* Type in some room name, e.g. `lobby` and hit Enter
* You should land on the page <http://127.0.0.1:8000/chat/lobby/> and see the the chat log and a message input. Type a message and hit Enter. The input will be cleared but nothing will show up in the chat log.
* Take a look into the console of the browser: you will see the message "Chat socket closed unexpectedly", which we defined earlier. That's because we haven't told Django yet, how to handle this WebSocket connection!
* Stop the Server and go back to your IDE

### Write your first consumer

* Create two new files: `chat/consumers.py` and `chat/routing.py`
  * the `routing.py` is similar to the `urls.py` but for websockets: it defines the urlpatterns and points to the corresponding Consumer
  * the `consumers.py` is similar to the `views.py` but for websockets: it handles receiving and sending messages as well as (dis)connecting to the WebSocket
* Inside `chat/consumers.py`, write

  ```
  # chat/consumers.py
  import json
  from channels.generic.websocket import WebsocketConsumer
  
  class ChatConsumer(WebsocketConsumer):
      def connect(self):
          self.accept()
  
      def disconnect(self, close_code):
          pass
  
      def receive(self, text_data=None, bytes_data=None):
          text_data_json = json.loads(text_data)
          message = text_data_json['message']
  
          self.send(text_data=json.dumps({
              'message': message
          }))
  ```
  * For now, this consumer only sends any received messages back to itself, no other clients will receive them
* Inside `chat/routing.py`, write

  ```
  # chat/routing.py
  from django.urls import re_path
  
  from . import consumers
  
  websocket_urlpatterns = [
      re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
  ]
  ```
* We still need to tell Django where to find our routing configuration. Inside `mysite/asgi.py`:

  ```
  # mysite/asgi.py
  import os
  
  from channels.auth import AuthMiddlewareStack
  from channels.routing import ProtocolTypeRouter, URLRouter
  from django.core.asgi import get_asgi_application
  import chat.routing
  
  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
  
  application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
          URLRouter(
              chat.routing.websocket_urlpatterns
          )
      ),
  })
  ```
* Instantiate the database by running `$ python manage.py migrate`
* See if everything is working so far by running `$ python manage.py runserver`
  * Go to <http://127.0.0.1:8000/chat/lobby/> and send yourself a message, you should see it appear in the chat log
  * Open the same page in a second tab and send another message. The message will only appear in the tab you sent it from, but not in the other one. That's because the messages are not broadcasted to other clients yet. Let's do that!

### Enable a channel layer

* Let's have a look at two new concepts:
  * A **channel** is a mailbox where messages can be sent to. Each channel has a name. Anyone who has the name of a channel can send a message to the channel.
  * A **group** is a group of related channels. A group has a name. Anyone who has the name of a group can add/remove a channel to the group by name and send a message to all channels in the group. It is not possible to enumerate what channels are in a particular group.
* Every consumer instance has an automatically generated unique channel name, and so can be communicated with via a channel layer.
* Go to `mysite/settings.py` and add a new variable below the `ASGI_APPLICATION`:

  ```
  CHANNEL_LAYERS = {
      "default": {
          "BACKEND": "channels.layers.InMemoryChannelLayer"
      }
  }
  ```
  * For production use, make sure to use a Redis Channel Layer, see <https://channels.readthedocs.io/en/stable/topics/channel_layers.html> for details
* Let’s make sure that the channel layer works:

  ```
  $ python3 manage.py shell
  >>> import channels.layers
  >>> channel_layer = channels.layers.get_channel_layer()
  >>> from asgiref.sync import async_to_sync
  >>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})
  >>> async_to_sync(channel_layer.receive)('test_channel')
  {'type': 'hello'}
  ```
  * Note: The async_to_sync(…) wrapper is required because ChatConsumer is a synchronous WebsocketConsumer but it is calling an asynchronous channel layer method. (All channel layer methods are asynchronous.)
* Now, let's rework the `ChatConsumer` in `chat/consumers.py` to use the Channel Layer:

  ```
  # chat/consumers.py
  import json
  from asgiref.sync import async_to_sync
  from channels.generic.websocket import WebsocketConsumer
  
  
  class ChatConsumer(WebsocketConsumer):
      def connect(self):
          self.room_name = self.scope['url_route']['kwargs']['room_name']
          self.room_group_name = 'chat_%s' % self.room_name
  
          # Join room group
          async_to_sync(self.channel_layer.group_add)(
              self.room_group_name,
              self.channel_name
          )
  
          self.accept()
  
      def disconnect(self, close_code):
          # Leave room group
          async_to_sync(self.channel_layer.group_discard)(
              self.room_group_name,
              self.channel_name
          )
  
      # Receive message from WebSocket
      def receive(self, text_data):
          text_data_json = json.loads(text_data)
          message = text_data_json['message']
  
          # Send message to room group
          async_to_sync(self.channel_layer.group_send)(
              self.room_group_name,
              {
                  'type': 'chat_message',
                  'message': message
              }
          )
  
      # Receive message from room group
      def chat_message(self, event):
          message = event['message']
  
          # Send message to WebSocket
          self.send(text_data=json.dumps({
              'message': message
          }))
  ```
  * Note regarding `async_to_sync(self.channel_layer.group_send):`

    An event has a special `'type'` key corresponding to the name of the method that should be invoked on consumers that receive the event.
* Now let's run the server again `$ python manage.py runserver`
  * Open <http://127.0.0.1:8000/chat/lobby/> in two tabs and send a message in one of them
  * You should now see the message also appearing in the second tab
* Congrats! You now have a basic fully-functional chat server!
Andreas Straßer's avatar
Andreas Straßer committed
424 425 426 427 428
* **See it in action on <http://soc-django.stusta.de/chat/>**  
  
* *(optional)* It is possible to rewrite the ChatConsumer to be asynchronous. This can lead to performance benefits, 
  if the Consumer does not call any regular synchronous I/O functions such as those that access Django models. Check out
  <https://channels.readthedocs.io/en/stable/tutorial/part_3.html> to learn more!
Andi's avatar
Andi committed
429 430 431 432 433 434 435 436 437

## Integration to Wahlfang

<https://gitlab.stusta.de/stustanet/wahlfang/-/issues/15>

* Issue #15: Update the Frontend automatically
* Automatically update the vote frontend, when the admin starts / stops election or publishes results, etc.
* Automatically update the manage frontend when a voter cast its vote (count the "Cast" counter up and the "Open" counter down)
* (Currently the page has to be reloaded for changes to appear)