From 11cfdcae6f7576a211183a11f8378197333f5d69 Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Sun, 17 Oct 2021 11:43:45 +0300 Subject: [PATCH] Fix some type hinting issues --- sanic/server/protocols/websocket_protocol.py | 24 +++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/sanic/server/protocols/websocket_protocol.py b/sanic/server/protocols/websocket_protocol.py index 95fa833a9a..674ec5a378 100644 --- a/sanic/server/protocols/websocket_protocol.py +++ b/sanic/server/protocols/websocket_protocol.py @@ -1,7 +1,8 @@ -from typing import TYPE_CHECKING, Optional, Sequence +from typing import TYPE_CHECKING, Optional, Sequence, cast from websockets.connection import CLOSED, CLOSING, OPEN from websockets.server import ServerConnection +from websockets.typing import Subprotocol from sanic.exceptions import ServerError from sanic.log import error_logger @@ -15,13 +16,6 @@ class WebSocketProtocol(HttpProtocol): - - websocket: Optional[WebsocketImplProtocol] - websocket_timeout: float - websocket_max_size = Optional[int] - websocket_ping_interval = Optional[float] - websocket_ping_timeout = Optional[float] - def __init__( self, *args, @@ -35,7 +29,7 @@ def __init__( **kwargs, ): super().__init__(*args, **kwargs) - self.websocket = None + self.websocket: Optional[WebsocketImplProtocol] = None self.websocket_timeout = websocket_timeout self.websocket_max_size = websocket_max_size if websocket_max_queue is not None and websocket_max_queue > 0: @@ -116,7 +110,15 @@ async def websocket_handshake( if subprotocols is not None: # subprotocols can be a set or frozenset, # but ServerConnection needs a list - subprotocols = list(subprotocols) + subprotocols = cast( + Optional[Sequence[Subprotocol]], + list( + [ + Subprotocol(subprotocol) + for subprotocol in subprotocols + ] + ), + ) ws_conn = ServerConnection( max_size=self.websocket_max_size, subprotocols=subprotocols, @@ -142,7 +144,7 @@ async def websocket_handshake( ) rbody += "".join(f"{k}: {v}\r\n" for k, v in resp.headers.items()) if resp.body is not None: - rbody += f"\r\n{resp.body}\r\n\r\n" + rbody += f"\r\n{resp.body.decode('utf-8')}\r\n\r\n" else: rbody += "\r\n" await super().send(rbody.encode())