File: disconnections.rst

package info (click to toggle)
quart 0.20.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,888 kB
  • sloc: python: 8,644; makefile: 42; sh: 17; sql: 6
file content (39 lines) | stat: -rw-r--r-- 1,129 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
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
.. _detecting_disconnection:

Detecting disconnection
=======================

If in your route or websocket handler (or code called from within it)
you are awaiting and the client disconnects the await will raise a
``CancelledError``. This can be used to detect when a client
disconnects, to allow for cleanup, for example the sse handler from
the :ref:`broadcast_tutorial` uses this to remove clients on
disconnect,

.. code-block:: python

    @app.route('/sse')
    async def sse():
        queue = asyncio.Queue()
        app.clients.add(queue)
        async def send_events():
            while True:
                try:
                    data = await queue.get()
                    event = ServerSentEvent(data)
                    yield event.encode()
                except asyncio.CancelledError:
                    app.clients.remove(queue)

or with only the relevant parts,

.. code-block:: python

    @app.route('/sse')
    async def sse():
        try:
            await ...
        except asyncio.CancelledError:
            # Has disconnected

The same applies for WebSockets, streaming the request, etc...