Skip to content

Commit e06d0cd

Browse files
committed
Small changes across files, comments, typing
1 parent 9b49df8 commit e06d0cd

File tree

3 files changed

+20
-19
lines changed

3 files changed

+20
-19
lines changed

adafruit_httpserver/request.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
1-
from typing import Dict, Tuple
1+
try:
2+
from typing import Dict, Tuple
3+
except ImportError:
4+
pass
25

36

47
class HTTPRequest:
58

69
method: str
710
path: str
8-
query_params: Dict[str, str] = {}
11+
query_params: Dict[str, str]
912
http_version: str
1013

11-
headers: Dict[str, str] = {}
14+
headers: Dict[str, str]
1215
body: bytes | None
1316

1417
raw_request: bytes
@@ -21,15 +24,15 @@ def __init__(
2124
if raw_request is None: raise ValueError("raw_request cannot be None")
2225

2326
try:
24-
self.method, self.path, self.query_params, self.http_version = self.parse_start_line(raw_request)
25-
self.headers = self.parse_headers(raw_request)
26-
self.body = self.parse_body(raw_request)
27+
self.method, self.path, self.query_params, self.http_version = self._parse_start_line(raw_request)
28+
self.headers = self._parse_headers(raw_request)
29+
self.body = self._parse_body(raw_request)
2730
except Exception as error:
2831
raise ValueError("Unparseable raw_request: ", raw_request) from error
2932

3033

3134
@staticmethod
32-
def parse_start_line(raw_request: bytes) -> Tuple(str, str, Dict[str, str], str):
35+
def _parse_start_line(raw_request: bytes) -> Tuple(str, str, Dict[str, str], str):
3336
"""Parse HTTP Start line to method, path, query_params and http_version."""
3437

3538
start_line = raw_request.decode("utf8").splitlines()[0]
@@ -45,7 +48,7 @@ def parse_start_line(raw_request: bytes) -> Tuple(str, str, Dict[str, str], str)
4548

4649

4750
@staticmethod
48-
def parse_headers(raw_request: bytes) -> Dict[str, str]:
51+
def _parse_headers(raw_request: bytes) -> Dict[str, str]:
4952
"""Parse HTTP headers from raw request."""
5053
parsed_request_lines = raw_request.decode("utf8").splitlines()
5154
empty_line = parsed_request_lines.index("")
@@ -54,7 +57,7 @@ def parse_headers(raw_request: bytes) -> Dict[str, str]:
5457

5558

5659
@staticmethod
57-
def parse_body(raw_request: bytes) -> Dict[str, str]:
60+
def _parse_body(raw_request: bytes) -> Dict[str, str]:
5861
"""Parse HTTP body from raw request."""
5962
parsed_request_lines = raw_request.decode("utf8").splitlines()
6063
empty_line = parsed_request_lines.index("")

adafruit_httpserver/response.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def __init__(
5353
def _construct_response_bytes(
5454
http_version: str = "HTTP/1.1",
5555
status: HTTPStatus = OK_200,
56-
content_type: str = "text/plain",
56+
content_type: str = MIMEType.TEXT_PLAIN,
5757
content_length: Union[int, None] = None,
5858
headers: Dict[str, str] = None,
5959
body: str = "",
@@ -64,9 +64,9 @@ def _construct_response_bytes(
6464

6565
headers = headers or {}
6666

67-
headers["Content-Type"] = content_type
68-
headers["Content-Length"] = content_length if content_length is not None else len(body)
69-
headers["Connection"] = "close"
67+
headers.setdefault("Content-Type", content_type)
68+
headers.setdefault("Content-Length", content_length if content_length is not None else len(body))
69+
headers.setdefault("Connection", "close")
7070

7171
for header, value in headers.items():
7272
response += f"{header}: {value}\r\n"

adafruit_httpserver/server.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
try:
2-
from typing import Any, Callable
2+
from typing import Callable, Protocol
33
except ImportError:
44
pass
55

@@ -14,9 +14,7 @@
1414
class HTTPServer:
1515
"""A basic socket-based HTTP server."""
1616

17-
def __init__(self, socket_source: Any) -> None:
18-
# TODO: Use a Protocol for the type annotation.
19-
# The Protocol could be refactored from adafruit_requests.
17+
def __init__(self, socket_source: Protocol) -> None:
2018
"""Create a server, and get it ready to run.
2119
2220
:param socket: An object that is a source of sockets. This could be a `socketpool`
@@ -99,8 +97,8 @@ def poll(self):
9997

10098
handler = self.route_handlers.get(HTTPRoute(request.path, request.method), None)
10199

102-
# If a handler for route exists, call it.
103-
if handler:
100+
# If a handler for route exists and is callable, call it.
101+
if handler is not None and callable(handler):
104102
response = handler(request)
105103

106104
# If no handler exists and request method is GET, try to serve a file.

0 commit comments

Comments
 (0)