Skip to content

Commit f1878b3

Browse files
committed
Replacing dict with HTTPHeaders in other modules
1 parent aad7010 commit f1878b3

File tree

2 files changed

+19
-30
lines changed

2 files changed

+19
-30
lines changed

adafruit_httpserver/request.py

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
except ImportError:
1313
pass
1414

15+
from .headers import HTTPHeaders
16+
1517

1618
class HTTPRequest:
1719
"""
@@ -39,20 +41,9 @@ class HTTPRequest:
3941
http_version: str
4042
"""HTTP version, e.g. "HTTP/1.1"."""
4143

42-
headers: Dict[str, str]
44+
headers: HTTPHeaders
4345
"""
44-
Headers from the request as `dict`.
45-
46-
Values should be accessed using **lower case header names**.
47-
48-
Example::
49-
50-
request.headers
51-
# {'connection': 'keep-alive', 'content-length': '64' ...}
52-
request.headers["content-length"]
53-
# '64'
54-
request.headers["Content-Length"]
55-
# KeyError: 'Content-Length'
46+
Headers from the request.
5647
"""
5748

5849
raw_request: bytes
@@ -120,12 +111,12 @@ def _parse_start_line(header_bytes: bytes) -> Tuple[str, str, Dict[str, str], st
120111
return method, path, query_params, http_version
121112

122113
@staticmethod
123-
def _parse_headers(header_bytes: bytes) -> Dict[str, str]:
114+
def _parse_headers(header_bytes: bytes) -> HTTPHeaders:
124115
"""Parse HTTP headers from raw request."""
125116
header_lines = header_bytes.decode("utf8").splitlines()[1:]
126117

127-
return {
128-
name.lower(): value
118+
return HTTPHeaders({
119+
name: value
129120
for header_line in header_lines
130121
for name, value in [header_line.split(": ", 1)]
131-
}
122+
})

adafruit_httpserver/response.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,15 @@
2020

2121
from .mime_type import MIMEType
2222
from .status import HTTPStatus, CommonHTTPStatus
23+
from .headers import HTTPHeaders
2324

2425

2526
class HTTPResponse:
2627
"""Details of an HTTP response. Use in `HTTPServer.route` decorator functions."""
2728

2829
http_version: str
2930
status: HTTPStatus
30-
headers: Dict[str, str]
31+
headers: HTTPHeaders
3132
content_type: str
3233

3334
filename: Optional[str]
@@ -39,7 +40,7 @@ def __init__( # pylint: disable=too-many-arguments
3940
self,
4041
status: Union[HTTPStatus, Tuple[int, str]] = CommonHTTPStatus.OK_200,
4142
body: str = "",
42-
headers: Dict[str, str] = None,
43+
headers: Union[HTTPHeaders, Dict[str, str]] = None,
4344
content_type: str = MIMEType.TYPE_TXT,
4445
filename: Optional[str] = None,
4546
root_path: str = "",
@@ -52,7 +53,7 @@ def __init__( # pylint: disable=too-many-arguments
5253
"""
5354
self.status = status if isinstance(status, HTTPStatus) else HTTPStatus(*status)
5455
self.body = body
55-
self.headers = headers or {}
56+
self.headers = headers.copy() if isinstance(headers, HTTPHeaders) else HTTPHeaders(headers)
5657
self.content_type = content_type
5758
self.filename = filename
5859
self.root_path = root_path
@@ -64,21 +65,18 @@ def _construct_response_bytes( # pylint: disable=too-many-arguments
6465
status: HTTPStatus = CommonHTTPStatus.OK_200,
6566
content_type: str = MIMEType.TYPE_TXT,
6667
content_length: Union[int, None] = None,
67-
headers: Dict[str, str] = None,
68+
headers: HTTPHeaders = None,
6869
body: str = "",
6970
) -> bytes:
7071
"""Constructs the response bytes from the given parameters."""
7172

7273
response = f"{http_version} {status.code} {status.text}\r\n"
7374

74-
# Make a copy of the headers so that we don't modify the incoming dict
75-
response_headers = {} if headers is None else headers.copy()
75+
headers.setdefault("Content-Type", content_type)
76+
headers.setdefault("Content-Length", content_length or len(body))
77+
headers.setdefault("Connection", "close")
7678

77-
response_headers.setdefault("Content-Type", content_type)
78-
response_headers.setdefault("Content-Length", content_length or len(body))
79-
response_headers.setdefault("Connection", "close")
80-
81-
for header, value in response_headers.items():
79+
for header, value in headers.items():
8280
response += f"{header}: {value}\r\n"
8381

8482
response += f"\r\n{body}"
@@ -122,7 +120,7 @@ def _send_response( # pylint: disable=too-many-arguments
122120
status: HTTPStatus,
123121
content_type: str,
124122
body: str,
125-
headers: Dict[str, str] = None,
123+
headers: HTTPHeaders = None,
126124
):
127125
self._send_bytes(
128126
conn,
@@ -140,7 +138,7 @@ def _send_file_response( # pylint: disable=too-many-arguments
140138
filename: str,
141139
root_path: str,
142140
file_length: int,
143-
headers: Dict[str, str] = None,
141+
headers: HTTPHeaders = None,
144142
):
145143
self._send_bytes(
146144
conn,

0 commit comments

Comments
 (0)