| 1 |
.. _websockets_discussion: |
| 2 |
|
| 3 |
Websockets |
| 4 |
========== |
| 5 |
|
| 6 |
Websockets start as a GET request that can either be upgraded to a |
| 7 |
websocket via a 101, switching protocols, response or any other |
| 8 |
response. The choice of what to do, or how to respond, is often not |
| 9 |
possible in other frameworks and is one of the motivating aims in |
| 10 |
Quart. In addition as websockets are very similar to requests, Quart |
| 11 |
aims to have analogues functionality between websockets and requests. |
| 12 |
|
| 13 |
Request analogues |
| 14 |
----------------- |
| 15 |
|
| 16 |
Websockets are very similar to GET requests, to the extent that is was |
| 17 |
tempting to simply extend the Flask request API to include websocket |
| 18 |
functionality. This would likely cause surprise to users of |
| 19 |
Flask-Sockets or Flask-SocketIO which set the de-facto Flask |
| 20 |
standard. Therefore I decided to introduce the websocket functionality |
| 21 |
alongside the existing request functionality. |
| 22 |
|
| 23 |
As websockets are so similar to GET requests it makes sense to produce |
| 24 |
an analogue for all the functionality available for requests. For |
| 25 |
example. :meth:`~quart.app.Quart.before_request` and |
| 26 |
:meth:`~quart.app.Quart.before_websocket` and there is a *websocket |
| 27 |
context* alongside the *request context*. |
| 28 |
|
| 29 |
Response or Upgrade |
| 30 |
------------------- |
| 31 |
|
| 32 |
The utility of being able to choose how to respond, or whether to |
| 33 |
upgrade, is best shown when considering authentication. In the example |
| 34 |
below a typical login_required decorator can be used to prevent |
| 35 |
unauthorised usage of the websocket. |
| 36 |
|
| 37 |
.. code-block:: python |
| 38 |
|
| 39 |
def login_required(func): |
| 40 |
@wraps(func) |
| 41 |
async def wrapper(*args, **kwargs): |
| 42 |
if websocket.authentication == (...): |
| 43 |
return await func(*args, **kwargs) |
| 44 |
else: |
| 45 |
abort(401) |
| 46 |
return wrapper |
| 47 |
|
| 48 |
@app.websocket('/ws') |
| 49 |
@login_required |
| 50 |
async def ws(): |
| 51 |
while True: |
| 52 |
await websocket.receive() |
| 53 |
... |
| 54 |
|
| 55 |
Quart also allows for the acceptance response (101) to be manually |
| 56 |
sent via :meth:`~quart.wrappers.Websocket.accept` as this gives the |
| 57 |
framework user full control. |
| 58 |
|
| 59 |
.. note:: |
| 60 |
|
| 61 |
This functionality is only useable with ASGI servers that |
| 62 |
implement the ``Websocket Denial Response`` extension. If the |
| 63 |
server does not support this extension Quart will instruct the |
| 64 |
server to close the connection without a response. Hypercorn, the |
| 65 |
recommended ASGI server, supports this extension. |