| 1 |
.. _chat_tutorial: |
| 2 |
|
| 3 |
Tutorial: Building a basic chat server |
| 4 |
====================================== |
| 5 |
|
| 6 |
In this tutorial we will build a very basic chat server. It will allow |
| 7 |
anyone to send messages to everyone else currently connected to the |
| 8 |
server. |
| 9 |
|
| 10 |
This tutorial is meant to serve as an introduction to WebSockets in |
| 11 |
Quart. If you want to skip to the end the code is on `Github |
| 12 |
<https://github.com/pallets/quart/tree/main/examples/chat>`_. |
| 13 |
|
| 14 |
1: Creating the project |
| 15 |
----------------------- |
| 16 |
|
| 17 |
We need to create a project for our chat server, I like to use `Poetry |
| 18 |
<https://python-poetry.org>`_ to do this. Poetry is installed via pip |
| 19 |
(or via `Brew <https://brew.sh/>`_): |
| 20 |
|
| 21 |
.. code-block:: console |
| 22 |
|
| 23 |
pip install poetry |
| 24 |
|
| 25 |
We can then use Poetry to create a new chat project: |
| 26 |
|
| 27 |
.. code-block:: console |
| 28 |
|
| 29 |
poetry new --src chat |
| 30 |
|
| 31 |
Our project can now be developed in the *chat* directory, and all |
| 32 |
subsequent commands should be in run the *chat* directory. |
| 33 |
|
| 34 |
2: Adding the dependencies |
| 35 |
-------------------------- |
| 36 |
|
| 37 |
We only need Quart to build this simple chat server, which we can |
| 38 |
install as a dependency of the project by running the following: |
| 39 |
|
| 40 |
.. code-block:: console |
| 41 |
|
| 42 |
poetry add quart |
| 43 |
|
| 44 |
Poetry will ensure that this dependency is present and the paths are |
| 45 |
correct by running: |
| 46 |
|
| 47 |
.. code-block:: console |
| 48 |
|
| 49 |
poetry install |
| 50 |
|
| 51 |
3: Creating the app |
| 52 |
------------------- |
| 53 |
|
| 54 |
We need a Quart app to be our web server, which is created by the |
| 55 |
following addition to *src/chat/__init__.py*: |
| 56 |
|
| 57 |
.. code-block:: python |
| 58 |
:caption: src/chat/__init__.py |
| 59 |
|
| 60 |
from quart import Quart |
| 61 |
|
| 62 |
app = Quart(__name__) |
| 63 |
|
| 64 |
def run() -> None: |
| 65 |
app.run() |
| 66 |
|
| 67 |
To make the app easy to run we can call the run method from a poetry |
| 68 |
script, by adding the following to *pyproject.toml*: |
| 69 |
|
| 70 |
.. code-block:: toml |
| 71 |
:caption: pyproject.toml |
| 72 |
|
| 73 |
[tool.poetry.scripts] |
| 74 |
start = "chat:run" |
| 75 |
|
| 76 |
Which allows the following command to start the app: |
| 77 |
|
| 78 |
.. code-block:: console |
| 79 |
|
| 80 |
poetry run start |
| 81 |
|
| 82 |
4: Serving the UI |
| 83 |
----------------- |
| 84 |
|
| 85 |
When users visit our chat website we will need to show them a UI which |
| 86 |
they can use to enter and receive messages. The following HTML |
| 87 |
template should be added to *src/chat/templates/index.html*: |
| 88 |
|
| 89 |
.. code-block:: html |
| 90 |
:caption: src/chat/templates/index.html |
| 91 |
|
| 92 |
<script type="text/javascript"> |
| 93 |
const ws = new WebSocket(`ws://${location.host}/ws`); |
| 94 |
|
| 95 |
ws.addEventListener('message', function (event) { |
| 96 |
const li = document.createElement("li"); |
| 97 |
li.appendChild(document.createTextNode(event.data)); |
| 98 |
document.getElementById("messages").appendChild(li); |
| 99 |
}); |
| 100 |
|
| 101 |
function send(event) { |
| 102 |
const message = (new FormData(event.target)).get("message"); |
| 103 |
if (message) { |
| 104 |
ws.send(message); |
| 105 |
} |
| 106 |
event.target.reset(); |
| 107 |
return false; |
| 108 |
} |
| 109 |
</script> |
| 110 |
|
| 111 |
<div style="display: flex; height: 100%; flex-direction: column"> |
| 112 |
<ul id="messages" style="flex-grow: 1; list-style-type: none"></ul> |
| 113 |
|
| 114 |
<form onsubmit="return send(event)"> |
| 115 |
<input type="text" name="message" minlength="1" /> |
| 116 |
<button type="submit">Send</button> |
| 117 |
</form> |
| 118 |
</div> |
| 119 |
|
| 120 |
This is a very basic UI both in terms of the styling, but also as |
| 121 |
there is no error handling for the WebSocket. |
| 122 |
|
| 123 |
We can now serve this template for the root path i.e. ``/`` by adding |
| 124 |
the following to *src/chat/__init__.py*: |
| 125 |
|
| 126 |
.. code-block:: python |
| 127 |
|
| 128 |
from quart import render_template |
| 129 |
|
| 130 |
@app.get("/") |
| 131 |
async def index(): |
| 132 |
return await render_template("index.html") |
| 133 |
|
| 134 |
5: Building a broker |
| 135 |
-------------------- |
| 136 |
|
| 137 |
Before we can add the websocket route we need to be able to pass |
| 138 |
messages from one connected client to another. For this we will need a |
| 139 |
message-broker. To start we'll build our own in memory broker by |
| 140 |
adding the following to *src/chat/broker.py*: |
| 141 |
|
| 142 |
.. code-block:: python |
| 143 |
:caption: src/chat/broker.py |
| 144 |
|
| 145 |
import asyncio |
| 146 |
from typing import AsyncGenerator |
| 147 |
|
| 148 |
from quart import Quart |
| 149 |
|
| 150 |
class Broker: |
| 151 |
def __init__(self) -> None: |
| 152 |
self.connections = set() |
| 153 |
|
| 154 |
async def publish(self, message: str) -> None: |
| 155 |
for connection in self.connections: |
| 156 |
await connection.put(message) |
| 157 |
|
| 158 |
async def subscribe(self) -> AsyncGenerator[str, None]: |
| 159 |
connection = asyncio.Queue() |
| 160 |
self.connections.add(connection) |
| 161 |
try: |
| 162 |
while True: |
| 163 |
yield await connection.get() |
| 164 |
finally: |
| 165 |
self.connections.remove(connection) |
| 166 |
|
| 167 |
This ``Broker`` has a publish-subscibe pattern based interface, with |
| 168 |
clients expected to publish messages to other clients whilst |
| 169 |
subscribing to any messages sent. |
| 170 |
|
| 171 |
6: Implementing the websocket |
| 172 |
----------------------------- |
| 173 |
|
| 174 |
We can now implement the websocket route, by adding the following to |
| 175 |
*src/chat/__init__.py*: |
| 176 |
|
| 177 |
.. code-block:: python |
| 178 |
:caption: src/chat/__init__.py |
| 179 |
|
| 180 |
import asyncio |
| 181 |
|
| 182 |
from quart import websocket |
| 183 |
|
| 184 |
from chat.broker import Broker |
| 185 |
|
| 186 |
broker = Broker() |
| 187 |
|
| 188 |
async def _receive() -> None: |
| 189 |
while True: |
| 190 |
message = await websocket.receive() |
| 191 |
await broker.publish(message) |
| 192 |
|
| 193 |
@app.websocket("/ws") |
| 194 |
async def ws() -> None: |
| 195 |
try: |
| 196 |
task = asyncio.ensure_future(_receive()) |
| 197 |
async for message in broker.subscribe(): |
| 198 |
await websocket.send(message) |
| 199 |
finally: |
| 200 |
task.cancel() |
| 201 |
await task |
| 202 |
|
| 203 |
The ``_receive`` coroutine must run as a separate task to ensure that |
| 204 |
sending and receiving run concurrently. In addition this task must be |
| 205 |
properly cancelled and cleaned up. |
| 206 |
|
| 207 |
When the user disconnects a CancelledError will be raised breaking the |
| 208 |
while loops and triggering the finally blocks. |
| 209 |
|
| 210 |
7: Testing |
| 211 |
---------- |
| 212 |
|
| 213 |
To test our app we need to check that messages sent via the websocket |
| 214 |
route are echoed back. This is done by adding the following to |
| 215 |
*tests/test_chat.py*: |
| 216 |
|
| 217 |
.. code-block:: python |
| 218 |
:caption: tests/test_chat.py |
| 219 |
|
| 220 |
import asyncio |
| 221 |
|
| 222 |
from quart.testing.connections import TestWebsocketConnection as _TestWebsocketConnection |
| 223 |
|
| 224 |
from chat import app |
| 225 |
|
| 226 |
async def _receive(test_websocket: _TestWebsocketConnection) -> str: |
| 227 |
return await test_websocket.receive() |
| 228 |
|
| 229 |
async def test_websocket() -> None: |
| 230 |
test_client = app.test_client() |
| 231 |
async with test_client.websocket("/ws") as test_websocket: |
| 232 |
task = asyncio.ensure_future(_receive(test_websocket)) |
| 233 |
await test_websocket.send("message") |
| 234 |
result = await task |
| 235 |
assert result == "message" |
| 236 |
|
| 237 |
As the test is an async function we need to install `pytest-asyncio |
| 238 |
<https://github.com/pytest-dev/pytest-asyncio>`_ by running the |
| 239 |
following: |
| 240 |
|
| 241 |
.. code-block:: console |
| 242 |
|
| 243 |
poetry add --dev pytest-asyncio |
| 244 |
|
| 245 |
Once installed it needs to be configured by adding the following to |
| 246 |
*pyproject.toml*: |
| 247 |
|
| 248 |
.. code-block:: toml |
| 249 |
|
| 250 |
[tool.pytest.ini_options] |
| 251 |
asyncio_mode = "auto" |
| 252 |
|
| 253 |
Finally we can run the tests via this command: |
| 254 |
|
| 255 |
.. code-block:: console |
| 256 |
|
| 257 |
poetry run pytest tests/ |
| 258 |
|
| 259 |
If you are running this in the Quart example folder you'll need to add |
| 260 |
a ``-c pyproject.toml`` option to prevent pytest from using the Quart |
| 261 |
pytest configuration. |
| 262 |
|
| 263 |
8: Summary |
| 264 |
---------- |
| 265 |
|
| 266 |
The message-broker we've built so far only works in memory, which |
| 267 |
means that messages are only shared with users connected to the same |
| 268 |
server instance. To share messages across server instances we need to |
| 269 |
use a third party broker, such as redis via the `aioredis |
| 270 |
<https://aioredis.readthedocs.io>`_ library which supports a pub/sub |
| 271 |
interface. |