adafruit-circuitpython-httpserver 4.0.1__py3-none-any.whl → 4.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,172 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """
5
+ `adafruit_httpserver.request`
6
+ ====================================================
7
+ * Author(s): Dan Halbert, Michał Pokusa
8
+ """
9
+
10
+ try:
11
+ from typing import Dict, Tuple, Union, TYPE_CHECKING
12
+ from socket import socket
13
+ from socketpool import SocketPool
14
+
15
+ if TYPE_CHECKING:
16
+ from .server import Server
17
+ except ImportError:
18
+ pass
19
+
20
+ import json
21
+
22
+ from .headers import Headers
23
+
24
+
25
+ class Request:
26
+ """
27
+ Incoming request, constructed from raw incoming bytes.
28
+ It is passed as first argument to all route handlers.
29
+ """
30
+
31
+ server: "Server"
32
+ """
33
+ Server object that received the request.
34
+ """
35
+
36
+ connection: Union["SocketPool.Socket", "socket.socket"]
37
+ """
38
+ Socket object used to send and receive data on the connection.
39
+ """
40
+
41
+ client_address: Tuple[str, int]
42
+ """
43
+ Address and port bound to the socket on the other end of the connection.
44
+
45
+ Example::
46
+
47
+ request.client_address
48
+ # ('192.168.137.1', 40684)
49
+ """
50
+
51
+ method: str
52
+ """Request method e.g. "GET" or "POST"."""
53
+
54
+ path: str
55
+ """Path of the request, e.g. ``"/foo/bar"``."""
56
+
57
+ query_params: Dict[str, str]
58
+ """
59
+ Query/GET parameters in the request.
60
+
61
+ Example::
62
+
63
+ request = Request(raw_request=b"GET /?foo=bar HTTP/1.1...")
64
+ request.query_params
65
+ # {"foo": "bar"}
66
+ """
67
+
68
+ http_version: str
69
+ """HTTP version, e.g. ``"HTTP/1.1"``."""
70
+
71
+ headers: Headers
72
+ """
73
+ Headers from the request.
74
+ """
75
+
76
+ raw_request: bytes
77
+ """
78
+ Raw 'bytes' that were received from the client.
79
+
80
+ Should **not** be modified directly.
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ server: "Server",
86
+ connection: Union["SocketPool.Socket", "socket.socket"],
87
+ client_address: Tuple[str, int],
88
+ raw_request: bytes = None,
89
+ ) -> None:
90
+ self.server = server
91
+ self.connection = connection
92
+ self.client_address = client_address
93
+ self.raw_request = raw_request
94
+
95
+ if raw_request is None:
96
+ raise ValueError("raw_request cannot be None")
97
+
98
+ header_bytes = self._raw_header_bytes
99
+
100
+ try:
101
+ (
102
+ self.method,
103
+ self.path,
104
+ self.query_params,
105
+ self.http_version,
106
+ ) = self._parse_start_line(header_bytes)
107
+ self.headers = self._parse_headers(header_bytes)
108
+ except Exception as error:
109
+ raise ValueError("Unparseable raw_request: ", raw_request) from error
110
+
111
+ @property
112
+ def body(self) -> bytes:
113
+ """Body of the request, as bytes."""
114
+ return self._raw_body_bytes
115
+
116
+ @body.setter
117
+ def body(self, body: bytes) -> None:
118
+ self.raw_request = self._raw_header_bytes + b"\r\n\r\n" + body
119
+
120
+ def json(self) -> Union[dict, None]:
121
+ """Body of the request, as a JSON-decoded dictionary."""
122
+ return json.loads(self.body) if self.body else None
123
+
124
+ @property
125
+ def _raw_header_bytes(self) -> bytes:
126
+ """Returns headers bytes."""
127
+ empty_line_index = self.raw_request.find(b"\r\n\r\n")
128
+
129
+ return self.raw_request[:empty_line_index]
130
+
131
+ @property
132
+ def _raw_body_bytes(self) -> bytes:
133
+ """Returns body bytes."""
134
+ empty_line_index = self.raw_request.find(b"\r\n\r\n")
135
+
136
+ return self.raw_request[empty_line_index + 4 :]
137
+
138
+ @staticmethod
139
+ def _parse_start_line(header_bytes: bytes) -> Tuple[str, str, Dict[str, str], str]:
140
+ """Parse HTTP Start line to method, path, query_params and http_version."""
141
+
142
+ start_line = header_bytes.decode("utf8").splitlines()[0]
143
+
144
+ method, path, http_version = start_line.split()
145
+
146
+ if "?" not in path:
147
+ path += "?"
148
+
149
+ path, query_string = path.split("?", 1)
150
+
151
+ query_params = {}
152
+ for query_param in query_string.split("&"):
153
+ if "=" in query_param:
154
+ key, value = query_param.split("=", 1)
155
+ query_params[key] = value
156
+ elif query_param:
157
+ query_params[query_param] = ""
158
+
159
+ return method, path, query_params, http_version
160
+
161
+ @staticmethod
162
+ def _parse_headers(header_bytes: bytes) -> Headers:
163
+ """Parse HTTP headers from raw request."""
164
+ header_lines = header_bytes.decode("utf8").splitlines()[1:]
165
+
166
+ return Headers(
167
+ {
168
+ name: value
169
+ for header_line in header_lines
170
+ for name, value in [header_line.split(": ", 1)]
171
+ }
172
+ )
@@ -0,0 +1,393 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """
5
+ `adafruit_httpserver.response`
6
+ ====================================================
7
+ * Author(s): Dan Halbert, Michał Pokusa
8
+ """
9
+
10
+ try:
11
+ from typing import Optional, Dict, Union, Tuple, Generator, Any
12
+ from socket import socket
13
+ from socketpool import SocketPool
14
+ except ImportError:
15
+ pass
16
+
17
+ import os
18
+ import json
19
+ from errno import EAGAIN, ECONNRESET
20
+
21
+ from .exceptions import (
22
+ BackslashInPathError,
23
+ FileNotExistsError,
24
+ ParentDirectoryReferenceError,
25
+ )
26
+ from .mime_types import MIMETypes
27
+ from .request import Request
28
+ from .status import Status, OK_200, TEMPORARY_REDIRECT_307, PERMANENT_REDIRECT_308
29
+ from .headers import Headers
30
+
31
+
32
+ class Response: # pylint: disable=too-few-public-methods
33
+ """
34
+ Response to a given `Request`. Use in `Server.route` handler functions.
35
+
36
+ Base class for all other response classes.
37
+
38
+ Example::
39
+
40
+ @server.route(path, method)
41
+ def route_func(request: Request):
42
+
43
+ return Response(request, body='Some content', content_type="text/plain")
44
+ """
45
+
46
+ def __init__( # pylint: disable=too-many-arguments
47
+ self,
48
+ request: Request,
49
+ body: Union[str, bytes] = "",
50
+ *,
51
+ status: Union[Status, Tuple[int, str]] = OK_200,
52
+ headers: Union[Headers, Dict[str, str]] = None,
53
+ content_type: str = None,
54
+ ) -> None:
55
+ """
56
+ :param Request request: Request that this is a response to.
57
+ :param str body: Body of response. Defaults to empty string.
58
+ :param Status status: Status code and text. Defaults to 200 OK.
59
+ :param Headers headers: Headers to include in response. Defaults to empty dict.
60
+ :param str content_type: Content type of response. Defaults to None.
61
+ """
62
+
63
+ self._request = request
64
+ self._body = body
65
+ self._status = status if isinstance(status, Status) else Status(*status)
66
+ self._headers = (
67
+ headers.copy() if isinstance(headers, Headers) else Headers(headers)
68
+ )
69
+ self._content_type = content_type
70
+ self._size = 0
71
+
72
+ def _send_headers(
73
+ self,
74
+ content_length: Optional[int] = None,
75
+ content_type: str = None,
76
+ ) -> None:
77
+ headers = self._headers.copy()
78
+
79
+ response_message_header = (
80
+ f"HTTP/1.1 {self._status.code} {self._status.text}\r\n"
81
+ )
82
+
83
+ headers.setdefault(
84
+ "Content-Type", content_type or self._content_type or MIMETypes.DEFAULT
85
+ )
86
+ headers.setdefault("Connection", "close")
87
+ if content_length is not None:
88
+ headers.setdefault("Content-Length", content_length)
89
+
90
+ for header, value in headers.items():
91
+ response_message_header += f"{header}: {value}\r\n"
92
+ response_message_header += "\r\n"
93
+
94
+ self._send_bytes(
95
+ self._request.connection, response_message_header.encode("utf-8")
96
+ )
97
+
98
+ def _send(self) -> None:
99
+ encoded_body = (
100
+ self._body.encode("utf-8") if isinstance(self._body, str) else self._body
101
+ )
102
+
103
+ self._send_headers(len(encoded_body), self._content_type)
104
+ self._send_bytes(self._request.connection, encoded_body)
105
+
106
+ def _send_bytes(
107
+ self,
108
+ conn: Union["SocketPool.Socket", "socket.socket"],
109
+ buffer: Union[bytes, bytearray, memoryview],
110
+ ):
111
+ bytes_sent: int = 0
112
+ bytes_to_send = len(buffer)
113
+ view = memoryview(buffer)
114
+ while bytes_sent < bytes_to_send:
115
+ try:
116
+ bytes_sent += conn.send(view[bytes_sent:])
117
+ except OSError as exc:
118
+ if exc.errno == EAGAIN:
119
+ continue
120
+ if exc.errno == ECONNRESET:
121
+ return
122
+ raise
123
+ self._size += bytes_sent
124
+
125
+
126
+ class FileResponse(Response): # pylint: disable=too-few-public-methods
127
+ """
128
+ Specialized version of `Response` class for sending files.
129
+
130
+ Instead of ``body`` it takes ``filename`` and ``root_path`` arguments.
131
+ It is also possible to send only headers with ``head_only`` argument or modify ``buffer_size``.
132
+
133
+ If browsers should download the file instead of displaying it, use ``as_attachment`` and
134
+ ``download_filename`` arguments.
135
+
136
+ Example::
137
+
138
+ @server.route(path, method)
139
+ def route_func(request: Request):
140
+
141
+ return FileResponse(request, filename='index.html', root_path='/www')
142
+ """
143
+
144
+ def __init__( # pylint: disable=too-many-arguments
145
+ self,
146
+ request: Request,
147
+ filename: str = "index.html",
148
+ root_path: str = None,
149
+ *,
150
+ status: Union[Status, Tuple[int, str]] = OK_200,
151
+ headers: Union[Headers, Dict[str, str]] = None,
152
+ content_type: str = None,
153
+ as_attachment: bool = False,
154
+ download_filename: str = None,
155
+ buffer_size: int = 1024,
156
+ head_only: bool = False,
157
+ safe: bool = True,
158
+ ) -> None:
159
+ """
160
+ :param Request request: Request that this is a response to.
161
+ :param str filename: Name of the file to send.
162
+ :param str root_path: Path to the root directory from which to serve files. Defaults to
163
+ server's ``root_path``.
164
+ :param Status status: Status code and text. Defaults to 200 OK.
165
+ :param Headers headers: Headers to include in response.
166
+ :param str content_type: Content type of response.
167
+ :param bool as_attachment: If True, the file will be sent as an attachment.
168
+ :param str download_filename: Name of the file to send as an attachment.
169
+ :param int buffer_size: Size of the buffer used to send the file. Defaults to 1024.
170
+ :param bool head_only: If True, only headers will be sent. Defaults to False.
171
+ :param bool safe: If True, checks if ``filename`` is valid. Defaults to True.
172
+ """
173
+ if safe:
174
+ self._verify_file_path_is_valid(filename)
175
+
176
+ super().__init__(
177
+ request=request,
178
+ headers=headers,
179
+ content_type=content_type,
180
+ status=status,
181
+ )
182
+ self._filename = filename + "index.html" if filename.endswith("/") else filename
183
+ self._root_path = root_path or self._request.server.root_path
184
+ self._full_file_path = self._combine_path(self._root_path, self._filename)
185
+ self._content_type = content_type or MIMETypes.get_for_filename(self._filename)
186
+ self._file_length = self._get_file_length(self._full_file_path)
187
+
188
+ self._buffer_size = buffer_size
189
+ self._head_only = head_only
190
+ self._safe = safe
191
+
192
+ if as_attachment:
193
+ self._headers.setdefault(
194
+ "Content-Disposition",
195
+ f"attachment; filename={download_filename or self._filename.split('/')[-1]}",
196
+ )
197
+
198
+ @staticmethod
199
+ def _verify_file_path_is_valid(file_path: str):
200
+ """
201
+ Verifies that ``file_path`` does not contain backslashes or parent directory references.
202
+
203
+ If not raises error corresponding to the problem.
204
+ """
205
+
206
+ # Check for backslashes
207
+ if "\\" in file_path: # pylint: disable=anomalous-backslash-in-string
208
+ raise BackslashInPathError(file_path)
209
+
210
+ # Check each component of the path for parent directory references
211
+ for part in file_path.split("/"):
212
+ if part == "..":
213
+ raise ParentDirectoryReferenceError(file_path)
214
+
215
+ @staticmethod
216
+ def _combine_path(root_path: str, filename: str) -> str:
217
+ """
218
+ Combines ``root_path`` and ``filename`` into a single path.
219
+ """
220
+
221
+ if not root_path.endswith("/"):
222
+ root_path += "/"
223
+ if filename.startswith("/"):
224
+ filename = filename[1:]
225
+
226
+ return root_path + filename
227
+
228
+ @staticmethod
229
+ def _get_file_length(file_path: str) -> int:
230
+ """
231
+ Tries to get the length of the file at ``file_path``.
232
+ Raises ``FileNotExistsError`` if file does not exist.
233
+ """
234
+ try:
235
+ stat = os.stat(file_path)
236
+ st_mode, st_size = stat[0], stat[6]
237
+ assert (st_mode & 0o170000) == 0o100000 # Check if it is a regular file
238
+ return st_size
239
+ except (OSError, AssertionError):
240
+ raise FileNotExistsError(file_path) # pylint: disable=raise-missing-from
241
+
242
+ def _send(self) -> None:
243
+ self._send_headers(self._file_length, self._content_type)
244
+
245
+ if not self._head_only:
246
+ with open(self._full_file_path, "rb") as file:
247
+ while bytes_read := file.read(self._buffer_size):
248
+ self._send_bytes(self._request.connection, bytes_read)
249
+
250
+
251
+ class ChunkedResponse(Response): # pylint: disable=too-few-public-methods
252
+ """
253
+ Specialized version of `Response` class for sending data using chunked transfer encoding.
254
+
255
+ Instead of requiring the whole content to be passed to the constructor, it expects
256
+ a **generator** that yields chunks of data.
257
+
258
+ Example::
259
+
260
+ @server.route(path, method)
261
+ def route_func(request: Request):
262
+
263
+ def body():
264
+ yield "Some ch"
265
+ yield "unked co"
266
+ yield "ntent"
267
+
268
+ return ChunkedResponse(request, body, content_type="text/plain")
269
+ """
270
+
271
+ def __init__( # pylint: disable=too-many-arguments
272
+ self,
273
+ request: Request,
274
+ body: Generator[Union[str, bytes], Any, Any],
275
+ *,
276
+ status: Union[Status, Tuple[int, str]] = OK_200,
277
+ headers: Union[Headers, Dict[str, str]] = None,
278
+ content_type: str = None,
279
+ ) -> None:
280
+ """
281
+ :param Request request: Request object
282
+ :param Generator body: Generator that yields chunks of data.
283
+ :param Status status: Status object or tuple with code and message.
284
+ :param Headers headers: Headers to be sent with the response.
285
+ :param str content_type: Content type of the response.
286
+ """
287
+
288
+ super().__init__(
289
+ request=request,
290
+ headers=headers,
291
+ status=status,
292
+ content_type=content_type,
293
+ )
294
+ self._headers.setdefault("Transfer-Encoding", "chunked")
295
+ self._body = body
296
+
297
+ def _send_chunk(self, chunk: Union[str, bytes] = "") -> None:
298
+ encoded_chunk = chunk.encode("utf-8") if isinstance(chunk, str) else chunk
299
+
300
+ self._send_bytes(self._request.connection, b"%x\r\n" % len(encoded_chunk))
301
+ self._send_bytes(self._request.connection, encoded_chunk)
302
+ self._send_bytes(self._request.connection, b"\r\n")
303
+
304
+ def _send(self) -> None:
305
+ self._send_headers()
306
+
307
+ for chunk in self._body():
308
+ self._send_chunk(chunk)
309
+
310
+ # Empty chunk to indicate end of response
311
+ self._send_chunk()
312
+
313
+
314
+ class JSONResponse(Response): # pylint: disable=too-few-public-methods
315
+ """
316
+ Specialized version of `Response` class for sending JSON data.
317
+
318
+ Instead of requiring ``body`` to be passed to the constructor, it expects ``data`` to be passed
319
+ instead.
320
+
321
+ Example::
322
+
323
+ @server.route(path, method)
324
+ def route_func(request: Request):
325
+
326
+ return JSONResponse(request, {"key": "value"})
327
+ """
328
+
329
+ def __init__(
330
+ self,
331
+ request: Request,
332
+ data: Dict[Any, Any],
333
+ *,
334
+ headers: Union[Headers, Dict[str, str]] = None,
335
+ status: Union[Status, Tuple[int, str]] = OK_200,
336
+ ) -> None:
337
+ """
338
+ :param Request request: Request that this is a response to.
339
+ :param dict data: Data to be sent as JSON.
340
+ :param Headers headers: Headers to include in response.
341
+ :param Status status: Status code and text. Defaults to 200 OK.
342
+ """
343
+ super().__init__(
344
+ request=request,
345
+ headers=headers,
346
+ status=status,
347
+ )
348
+ self._data = data
349
+
350
+ def _send(self) -> None:
351
+ encoded_data = json.dumps(self._data).encode("utf-8")
352
+
353
+ self._send_headers(len(encoded_data), "application/json")
354
+ self._send_bytes(self._request.connection, encoded_data)
355
+
356
+
357
+ class Redirect(Response): # pylint: disable=too-few-public-methods
358
+ """
359
+ Specialized version of `Response` class for redirecting to another URL.
360
+
361
+ Instead of requiring the body to be passed to the constructor, it expects a URL to redirect to.
362
+
363
+ Example::
364
+
365
+ @server.route(path, method)
366
+ def route_func(request: Request):
367
+
368
+ return Redirect(request, "https://www.example.com")
369
+ """
370
+
371
+ def __init__(
372
+ self,
373
+ request: Request,
374
+ url: str,
375
+ *,
376
+ permanent: bool = False,
377
+ headers: Union[Headers, Dict[str, str]] = None,
378
+ ) -> None:
379
+ """
380
+ :param Request request: Request that this is a response to.
381
+ :param str url: URL to redirect to.
382
+ :param bool permanent: Whether to use a permanent redirect (308) or a temporary one (307).
383
+ :param Headers headers: Headers to include in response.
384
+ """
385
+ super().__init__(
386
+ request,
387
+ status=PERMANENT_REDIRECT_308 if permanent else TEMPORARY_REDIRECT_307,
388
+ headers=headers,
389
+ )
390
+ self._headers.update({"Location": url})
391
+
392
+ def _send(self) -> None:
393
+ self._send_headers()