Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correctly handle headers of different types #152

Merged
merged 1 commit into from
Feb 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion adafruit_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)}"
)
Comment on lines +540 to +542
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in CPython requests this is:

        raise InvalidHeader(
            f"Invalid leading whitespace, reserved character(s), or return "
            f"character(s) in header {header_kind}: {header_part!r}"
        )

An AttributeError seems similar enough and didn't know if creating a new Exception would be wanted


@staticmethod
def _send(socket: SocketType, data: bytes):
total_sent = 0
Expand All @@ -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:
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In CPython requests they have a method merge_setting

That they use in a bunch of places, but it creates new dict objects, and thought this would be simpler in memory usage

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
Expand All @@ -571,6 +588,9 @@ def _send_request(
data: Any,
json: Any,
):
# Check headers
self._check_headers(headers)

# Convert data
content_type_header = None

Expand Down