From 3bf143fac74a0691ac10d6db370a12e0e3ed7c7f Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Fri, 26 Jan 2024 08:52:18 -0800 Subject: [PATCH] Correctly handle headers of different types --- adafruit_requests.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/adafruit_requests.py b/adafruit_requests.py index 26b40f0..c700a8d 100644 --- a/adafruit_requests.py +++ b/adafruit_requests.py @@ -529,6 +529,18 @@ def _get_socket( self._socket_free[sock] = False return sock + @staticmethod + def _check_headers(headers: Dict[str, str]): + if not isinstance(headers, dict): + raise AttributeError("headers must be in dict format") + + for key, value in headers.items(): + if isinstance(value, (str, bytes)) or value is None: + continue + raise AttributeError( + f"Header part ({value}) from {key} must be of type str or bytes, not {type(value)}" + ) + @staticmethod def _send(socket: SocketType, data: bytes): total_sent = 0 @@ -555,9 +567,14 @@ def _send_as_bytes(self, socket: SocketType, data: str): return self._send(socket, bytes(data, "utf-8")) def _send_header(self, socket, header, value): + if value is None: + return self._send_as_bytes(socket, header) self._send(socket, b": ") - self._send_as_bytes(socket, value) + if isinstance(value, bytes): + self._send(socket, value) + else: + self._send_as_bytes(socket, value) self._send(socket, b"\r\n") # pylint: disable=too-many-arguments @@ -571,6 +588,9 @@ def _send_request( data: Any, json: Any, ): + # Check headers + self._check_headers(headers) + # Convert data content_type_header = None