adafruit-circuitpython-httpserver 4.0.0__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,159 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """
5
+ `adafruit_httpserver.route`
6
+ ====================================================
7
+ * Author(s): Dan Halbert, Michał Pokusa
8
+ """
9
+
10
+ try:
11
+ from typing import Callable, List, Set, Union, Tuple, TYPE_CHECKING
12
+
13
+ if TYPE_CHECKING:
14
+ from .response import Response
15
+ except ImportError:
16
+ pass
17
+
18
+ import re
19
+
20
+ from .methods import GET
21
+
22
+
23
+ class _Route:
24
+ """Route definition for different paths, see `adafruit_httpserver.server.Server.route`."""
25
+
26
+ def __init__(
27
+ self,
28
+ path: str = "",
29
+ methods: Union[str, Set[str]] = GET,
30
+ append_slash: bool = False,
31
+ ) -> None:
32
+ self._validate_path(path)
33
+
34
+ self.parameters_names = [
35
+ name[1:-1] for name in re.compile(r"/[^<>]*/?").split(path) if name != ""
36
+ ]
37
+ self.path = re.sub(r"<\w+>", r"([^/]+)", path).replace("....", r".+").replace(
38
+ "...", r"[^/]+"
39
+ ) + ("/?" if append_slash else "")
40
+ self.methods = methods if isinstance(methods, set) else {methods}
41
+
42
+ @staticmethod
43
+ def _validate_path(path: str) -> None:
44
+ if not path.startswith("/"):
45
+ raise ValueError("Path must start with a slash.")
46
+
47
+ if "<>" in path:
48
+ raise ValueError("All URL parameters must be named.")
49
+
50
+ def match(self, other: "_Route") -> Tuple[bool, List[str]]:
51
+ """
52
+ Checks if the route matches the other route.
53
+
54
+ If the route contains parameters, it will check if the ``other`` route contains values for
55
+ them.
56
+
57
+ Returns tuple of a boolean and a list of strings. The boolean indicates if the routes match,
58
+ and the list contains the values of the url parameters from the ``other`` route.
59
+
60
+ Examples::
61
+
62
+ route = _Route("/example", GET, True)
63
+
64
+ other1a = _Route("/example", GET)
65
+ other1b = _Route("/example/", GET)
66
+ route.matches(other1a) # True, []
67
+ route.matches(other1b) # True, []
68
+
69
+ other2 = _Route("/other-example", GET)
70
+ route.matches(other2) # False, []
71
+
72
+ ...
73
+
74
+ route = _Route("/example/<parameter>", GET)
75
+
76
+ other1 = _Route("/example/123", GET)
77
+ route.matches(other1) # True, ["123"]
78
+
79
+ other2 = _Route("/other-example", GET)
80
+ route.matches(other2) # False, []
81
+
82
+ ...
83
+
84
+ route1 = _Route("/example/.../something", GET)
85
+ other1 = _Route("/example/123/something", GET)
86
+ route1.matches(other1) # True, []
87
+
88
+ route2 = _Route("/example/..../something", GET)
89
+ other2 = _Route("/example/123/456/something", GET)
90
+ route2.matches(other2) # True, []
91
+ """
92
+
93
+ if not other.methods.issubset(self.methods):
94
+ return False, []
95
+
96
+ regex_match = re.match(f"^{self.path}$", other.path)
97
+ if regex_match is None:
98
+ return False, []
99
+
100
+ return True, regex_match.groups()
101
+
102
+ def __repr__(self) -> str:
103
+ path = repr(self.path)
104
+ methods = repr(self.methods)
105
+
106
+ return f"_Route(path={path}, methods={methods})"
107
+
108
+
109
+ class _Routes:
110
+ """A collection of routes and their corresponding handlers."""
111
+
112
+ def __init__(self) -> None:
113
+ self._routes: List[_Route] = []
114
+ self._handlers: List[Callable] = []
115
+
116
+ def add(self, route: _Route, handler: Callable):
117
+ """Adds a route and its handler to the collection."""
118
+
119
+ self._routes.append(route)
120
+ self._handlers.append(handler)
121
+
122
+ def find_handler(self, route: _Route) -> Union[Callable["...", "Response"], None]:
123
+ """
124
+ Finds a handler for a given route.
125
+
126
+ If route used URL parameters, the handler will be wrapped to pass the parameters to the
127
+ handler.
128
+
129
+ Example::
130
+
131
+ @server.route("/example/<my_parameter>", GET)
132
+ def route_func(request, my_parameter):
133
+ ...
134
+ request.path == "/example/123" # True
135
+ my_parameter == "123" # True
136
+ """
137
+ found_route, _route = False, None
138
+
139
+ for _route in self._routes:
140
+ matches, parameters_values = _route.match(route)
141
+
142
+ if matches:
143
+ found_route = True
144
+ break
145
+
146
+ if not found_route:
147
+ return None
148
+
149
+ handler = self._handlers[self._routes.index(_route)]
150
+
151
+ keyword_parameters = dict(zip(_route.parameters_names, parameters_values))
152
+
153
+ def wrapped_handler(request):
154
+ return handler(request, **keyword_parameters)
155
+
156
+ return wrapped_handler
157
+
158
+ def __repr__(self) -> str:
159
+ return f"_Routes({repr(self._routes)})"
@@ -0,0 +1,453 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """
5
+ `adafruit_httpserver.server`
6
+ ====================================================
7
+ * Author(s): Dan Halbert, Michał Pokusa
8
+ """
9
+
10
+ try:
11
+ from typing import Callable, Protocol, Union, List, Set, Tuple
12
+ from socket import socket
13
+ from socketpool import SocketPool
14
+ except ImportError:
15
+ pass
16
+
17
+ from errno import EAGAIN, ECONNRESET, ETIMEDOUT
18
+ from traceback import print_exception
19
+
20
+ from .authentication import Basic, Bearer, require_authentication
21
+ from .exceptions import (
22
+ ServerStoppedError,
23
+ AuthenticationError,
24
+ FileNotExistsError,
25
+ InvalidPathError,
26
+ ServingFilesDisabledError,
27
+ )
28
+ from .methods import GET, HEAD
29
+ from .request import Request
30
+ from .response import Response, FileResponse
31
+ from .route import _Routes, _Route
32
+ from .status import BAD_REQUEST_400, UNAUTHORIZED_401, FORBIDDEN_403, NOT_FOUND_404
33
+
34
+
35
+ class Server:
36
+ """A basic socket-based HTTP server."""
37
+
38
+ host: str = None
39
+ """Host name or IP address the server is listening on."""
40
+
41
+ port: int = None
42
+ """Port the server is listening on."""
43
+
44
+ def __init__(
45
+ self, socket_source: Protocol, root_path: str = None, *, debug: bool = False
46
+ ) -> None:
47
+ """Create a server, and get it ready to run.
48
+
49
+ :param socket: An object that is a source of sockets. This could be a `socketpool`
50
+ in CircuitPython or the `socket` module in CPython.
51
+ :param str root_path: Root directory to serve files from
52
+ :param bool debug: Enables debug messages useful during development
53
+ """
54
+ self._auths = []
55
+ self._buffer = bytearray(1024)
56
+ self._timeout = 1
57
+ self._routes = _Routes()
58
+ self._socket_source = socket_source
59
+ self._sock = None
60
+ self.root_path = root_path
61
+ if root_path in ["", "/"] and debug:
62
+ _debug_warning_exposed_files(root_path)
63
+ self.stopped = False
64
+
65
+ self.debug = debug
66
+
67
+ def route(
68
+ self,
69
+ path: str,
70
+ methods: Union[str, Set[str]] = GET,
71
+ *,
72
+ append_slash: bool = False,
73
+ ) -> Callable:
74
+ """
75
+ Decorator used to add a route.
76
+
77
+ If request matches multiple routes, the first matched one added will be used.
78
+
79
+ :param str path: URL path
80
+ :param str methods: HTTP method(s): ``"GET"``, ``"POST"``, ``["GET", "POST"]`` etc.
81
+ :param bool append_slash: If True, the route will be accessible with and without a
82
+ trailing slash
83
+
84
+ Example::
85
+
86
+ # Default method is GET
87
+ @server.route("/example")
88
+ def route_func(request):
89
+ ...
90
+
91
+ # It is necessary to specify other methods like POST, PUT, etc.
92
+ @server.route("/example", POST)
93
+ def route_func(request):
94
+ ...
95
+
96
+ # If you want to access URL with and without trailing slash, use append_slash=True
97
+ @server.route("/example-with-slash", append_slash=True)
98
+ # which is equivalent to
99
+ @server.route("/example-with-slash")
100
+ @server.route("/example-with-slash/")
101
+ def route_func(request):
102
+ ...
103
+
104
+ # Multiple methods can be specified
105
+ @server.route("/example", [GET, POST])
106
+ def route_func(request):
107
+ ...
108
+
109
+ # URL parameters can be specified
110
+ @server.route("/example/<my_parameter>", GET) e.g. /example/123
111
+ def route_func(request, my_parameter):
112
+ ...
113
+
114
+ # It is possible to use wildcard that can match any number of path segments
115
+ @server.route("/example/.../something", GET) # e.g. /example/123/something
116
+ @server.route("/example/..../something", GET) # e.g. /example/123/456/something
117
+ def route_func(request):
118
+ ...
119
+ """
120
+ if path.endswith("/") and append_slash:
121
+ raise ValueError("Cannot use append_slash=True when path ends with /")
122
+
123
+ methods = set(methods) if isinstance(methods, (set, list)) else set([methods])
124
+
125
+ def route_decorator(func: Callable) -> Callable:
126
+ self._routes.add(_Route(path, methods, append_slash), func)
127
+ return func
128
+
129
+ return route_decorator
130
+
131
+ def _verify_can_start(self, host: str, port: int) -> None:
132
+ """Check if the server can be successfully started. Raises RuntimeError if not."""
133
+
134
+ if host is None or port is None:
135
+ raise RuntimeError("Host and port cannot be None")
136
+
137
+ try:
138
+ self._socket_source.getaddrinfo(host, port)
139
+ except OSError as error:
140
+ raise RuntimeError(f"Cannot start server on {host}:{port}") from error
141
+
142
+ def serve_forever(self, host: str, port: int = 80) -> None:
143
+ """
144
+ Wait for HTTP requests at the given host and port. Does not return.
145
+ Ignores any exceptions raised by the handler function and continues to serve.
146
+ Returns only when the server is stopped by calling ``.stop()``.
147
+
148
+ :param str host: host name or IP address
149
+ :param int port: port
150
+ """
151
+ self.start(host, port)
152
+
153
+ while not self.stopped:
154
+ try:
155
+ self.poll()
156
+ except KeyboardInterrupt: # Exit on Ctrl-C e.g. during development
157
+ self.stop()
158
+ return
159
+ except Exception: # pylint: disable=broad-except
160
+ pass # Ignore exceptions in handler function
161
+
162
+ def start(self, host: str, port: int = 80) -> None:
163
+ """
164
+ Start the HTTP server at the given host and port. Requires calling
165
+ ``.poll()`` in a while loop to handle incoming requests.
166
+
167
+ :param str host: host name or IP address
168
+ :param int port: port
169
+ """
170
+ self._verify_can_start(host, port)
171
+
172
+ self.host, self.port = host, port
173
+
174
+ self.stopped = False
175
+ self._sock = self._socket_source.socket(
176
+ self._socket_source.AF_INET, self._socket_source.SOCK_STREAM
177
+ )
178
+ self._sock.bind((host, port))
179
+ self._sock.listen(10)
180
+ self._sock.setblocking(False) # Non-blocking socket
181
+
182
+ if self.debug:
183
+ _debug_started_server(self)
184
+
185
+ def stop(self) -> None:
186
+ """
187
+ Stops the server from listening for new connections and closes the socket.
188
+ Current requests will be processed. Server can be started again by calling ``.start()``
189
+ or ``.serve_forever()``.
190
+ """
191
+ self.host, self.port = None, None
192
+
193
+ self.stopped = True
194
+ self._sock.close()
195
+
196
+ if self.debug:
197
+ _debug_stopped_server(self)
198
+
199
+ def _receive_request(
200
+ self,
201
+ sock: Union["SocketPool.Socket", "socket.socket"],
202
+ client_address: Tuple[str, int],
203
+ ) -> Request:
204
+ """Receive bytes from socket until the whole request is received."""
205
+
206
+ # Receiving data until empty line
207
+ header_bytes = self._receive_header_bytes(sock)
208
+
209
+ # Return if no data received
210
+ if not header_bytes:
211
+ return None
212
+
213
+ request = Request(self, sock, client_address, header_bytes)
214
+
215
+ content_length = int(request.headers.get("Content-Length", 0))
216
+ received_body_bytes = request.body
217
+
218
+ # Receiving remaining body bytes
219
+ request.body = self._receive_body_bytes(
220
+ sock, received_body_bytes, content_length
221
+ )
222
+
223
+ return request
224
+
225
+ def _receive_header_bytes(
226
+ self, sock: Union["SocketPool.Socket", "socket.socket"]
227
+ ) -> bytes:
228
+ """Receive bytes until a empty line is received."""
229
+ received_bytes = bytes()
230
+ while b"\r\n\r\n" not in received_bytes:
231
+ try:
232
+ length = sock.recv_into(self._buffer, len(self._buffer))
233
+ received_bytes += self._buffer[:length]
234
+ except OSError as ex:
235
+ if ex.errno == ETIMEDOUT:
236
+ break
237
+ raise
238
+ except Exception as ex:
239
+ raise ex
240
+ return received_bytes
241
+
242
+ def _receive_body_bytes(
243
+ self,
244
+ sock: Union["SocketPool.Socket", "socket.socket"],
245
+ received_body_bytes: bytes,
246
+ content_length: int,
247
+ ) -> bytes:
248
+ """Receive bytes until the given content length is received."""
249
+ while len(received_body_bytes) < content_length:
250
+ try:
251
+ length = sock.recv_into(self._buffer, len(self._buffer))
252
+ received_body_bytes += self._buffer[:length]
253
+ except OSError as ex:
254
+ if ex.errno == ETIMEDOUT:
255
+ break
256
+ raise
257
+ except Exception as ex:
258
+ raise ex
259
+ return received_body_bytes[:content_length]
260
+
261
+ def _handle_request(
262
+ self, request: Request, handler: Union[Callable, None]
263
+ ) -> Union[Response, None]:
264
+ try:
265
+ # Check server authentications if necessary
266
+ if self._auths:
267
+ require_authentication(request, self._auths)
268
+
269
+ # Handler for route exists and is callable
270
+ if handler is not None and callable(handler):
271
+ return handler(request)
272
+
273
+ # No root_path, access to filesystem disabled, return 404.
274
+ if self.root_path is None:
275
+ raise ServingFilesDisabledError
276
+
277
+ # Method is GET or HEAD, try to serve a file from the filesystem.
278
+ if request.method in [GET, HEAD]:
279
+ return FileResponse(
280
+ request,
281
+ filename=request.path,
282
+ root_path=self.root_path,
283
+ head_only=request.method == HEAD,
284
+ )
285
+
286
+ return Response(request, status=BAD_REQUEST_400)
287
+
288
+ except AuthenticationError:
289
+ return Response(
290
+ request,
291
+ status=UNAUTHORIZED_401,
292
+ headers={"WWW-Authenticate": 'Basic charset="UTF-8"'},
293
+ )
294
+
295
+ except InvalidPathError as error:
296
+ return Response(
297
+ request,
298
+ str(error) if self.debug else "Invalid path",
299
+ status=FORBIDDEN_403,
300
+ )
301
+
302
+ except (FileNotExistsError, ServingFilesDisabledError) as error:
303
+ return Response(
304
+ request,
305
+ str(error) if self.debug else "File not found",
306
+ status=NOT_FOUND_404,
307
+ )
308
+
309
+ def poll(self):
310
+ """
311
+ Call this method inside your main loop to get the server to check for new incoming client
312
+ requests. When a request comes in, it will be handled by the handler function.
313
+ """
314
+ if self.stopped:
315
+ raise ServerStoppedError
316
+
317
+ try:
318
+ conn, client_address = self._sock.accept()
319
+ with conn:
320
+ conn.settimeout(self._timeout)
321
+
322
+ # Receive the whole request
323
+ if (request := self._receive_request(conn, client_address)) is None:
324
+ return
325
+
326
+ # Find a handler for the route
327
+ handler = self._routes.find_handler(
328
+ _Route(request.path, request.method)
329
+ )
330
+
331
+ # Handle the request
332
+ response = self._handle_request(request, handler)
333
+
334
+ if response is None:
335
+ return
336
+
337
+ # Send the response
338
+ response._send() # pylint: disable=protected-access
339
+
340
+ if self.debug:
341
+ _debug_response_sent(response)
342
+
343
+ except Exception as error: # pylint: disable=broad-except
344
+ if isinstance(error, OSError):
345
+ # There is no data available right now, try again later.
346
+ if error.errno == EAGAIN:
347
+ return
348
+ # Connection reset by peer, try again later.
349
+ if error.errno == ECONNRESET:
350
+ return
351
+
352
+ if self.debug:
353
+ _debug_exception_in_handler(error)
354
+
355
+ raise error # Raise the exception again to be handled by the user.
356
+
357
+ def require_authentication(self, auths: List[Union[Basic, Bearer]]) -> None:
358
+ """
359
+ Requires authentication for all routes and files in ``root_path``.
360
+ Any non-authenticated request will be rejected with a 401 status code.
361
+
362
+ Example::
363
+
364
+ server = Server(pool, "/static")
365
+ server.require_authentication([Basic("user", "pass")])
366
+ """
367
+ self._auths = auths
368
+
369
+ @property
370
+ def request_buffer_size(self) -> int:
371
+ """
372
+ The maximum size of the incoming request buffer. If the default size isn't
373
+ adequate to handle your incoming data you can set this after creating the
374
+ server instance.
375
+
376
+ Default size is 1024 bytes.
377
+
378
+ Example::
379
+
380
+ server = Server(pool, "/static")
381
+ server.request_buffer_size = 2048
382
+
383
+ server.serve_forever(str(wifi.radio.ipv4_address))
384
+ """
385
+ return len(self._buffer)
386
+
387
+ @request_buffer_size.setter
388
+ def request_buffer_size(self, value: int) -> None:
389
+ self._buffer = bytearray(value)
390
+
391
+ @property
392
+ def socket_timeout(self) -> int:
393
+ """
394
+ Timeout after which the socket will stop waiting for more incoming data.
395
+
396
+ Must be set to positive integer or float. Default is 1 second.
397
+
398
+ When exceeded, raises `OSError` with `errno.ETIMEDOUT`.
399
+
400
+ Example::
401
+
402
+ server = Server(pool, "/static")
403
+ server.socket_timeout = 3
404
+
405
+ server.serve_forever(str(wifi.radio.ipv4_address))
406
+ """
407
+ return self._timeout
408
+
409
+ @socket_timeout.setter
410
+ def socket_timeout(self, value: int) -> None:
411
+ if isinstance(value, (int, float)) and value > 0:
412
+ self._timeout = value
413
+ else:
414
+ raise ValueError("Server.socket_timeout must be a positive numeric value.")
415
+
416
+
417
+ def _debug_warning_exposed_files(root_path: str):
418
+ """Warns about exposing all files on the device."""
419
+ print(
420
+ f"WARNING: Setting root_path to '{root_path}' will expose all files on your device through"
421
+ " the webserver, including potentially sensitive files like settings.toml or secrets.py. "
422
+ "Consider making a sub-directory on your device and using that for your root_path instead."
423
+ )
424
+
425
+
426
+ def _debug_started_server(server: "Server"):
427
+ """Prints a message when the server starts."""
428
+ host, port = server.host, server.port
429
+
430
+ print(f"Started development server on http://{host}:{port}")
431
+
432
+
433
+ def _debug_response_sent(response: "Response"):
434
+ """Prints a message when after a response is sent."""
435
+ # pylint: disable=protected-access
436
+ client_ip = response._request.client_address[0]
437
+ method = response._request.method
438
+ path = response._request.path
439
+ req_size = len(response._request.raw_request)
440
+ status = response._status
441
+ res_size = response._size
442
+
443
+ print(f'{client_ip} -- "{method} {path}" {req_size} -- "{status}" {res_size}')
444
+
445
+
446
+ def _debug_stopped_server(server: "Server"): # pylint: disable=unused-argument
447
+ """Prints a message after the server stops."""
448
+ print("Stopped development server")
449
+
450
+
451
+ def _debug_exception_in_handler(error: Exception):
452
+ """Prints a message when an exception is raised in a handler."""
453
+ print_exception(error)
@@ -0,0 +1,64 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """
5
+ `adafruit_httpserver.status`
6
+ ====================================================
7
+ * Author(s): Dan Halbert, Michał Pokusa
8
+ """
9
+
10
+
11
+ class Status: # pylint: disable=too-few-public-methods
12
+ """HTTP status code."""
13
+
14
+ def __init__(self, code: int, text: str):
15
+ """
16
+ Define a status code.
17
+
18
+ :param int code: Numeric value: 200, 404, etc.
19
+ :param str text: Short phrase: "OK", "Not Found', etc.
20
+ """
21
+ self.code = code
22
+ self.text = text
23
+
24
+ def __repr__(self):
25
+ return f'Status({self.code}, "{self.text}")'
26
+
27
+ def __str__(self):
28
+ return f"{self.code} {self.text}"
29
+
30
+ def __eq__(self, other: "Status"):
31
+ return self.code == other.code and self.text == other.text
32
+
33
+
34
+ OK_200 = Status(200, "OK")
35
+
36
+ CREATED_201 = Status(201, "Created")
37
+
38
+ ACCEPTED_202 = Status(202, "Accepted")
39
+
40
+ NO_CONTENT_204 = Status(204, "No Content")
41
+
42
+ PARTIAL_CONTENT_206 = Status(206, "Partial Content")
43
+
44
+ TEMPORARY_REDIRECT_307 = Status(307, "Temporary Redirect")
45
+
46
+ PERMANENT_REDIRECT_308 = Status(308, "Permanent Redirect")
47
+
48
+ BAD_REQUEST_400 = Status(400, "Bad Request")
49
+
50
+ UNAUTHORIZED_401 = Status(401, "Unauthorized")
51
+
52
+ FORBIDDEN_403 = Status(403, "Forbidden")
53
+
54
+ NOT_FOUND_404 = Status(404, "Not Found")
55
+
56
+ METHOD_NOT_ALLOWED_405 = Status(405, "Method Not Allowed")
57
+
58
+ TOO_MANY_REQUESTS_429 = Status(429, "Too Many Requests")
59
+
60
+ INTERNAL_SERVER_ERROR_500 = Status(500, "Internal Server Error")
61
+
62
+ NOT_IMPLEMENTED_501 = Status(501, "Not Implemented")
63
+
64
+ SERVICE_UNAVAILABLE_503 = Status(503, "Service Unavailable")
@@ -1,5 +0,0 @@
1
- adafruit_circuitpython_httpserver-4.0.0.dist-info/LICENSE,sha256=gyhZwtwoqSsDGoSrV4MrLpKKWyG_jE3eROTZp1EjIUM,1102
2
- adafruit_circuitpython_httpserver-4.0.0.dist-info/METADATA,sha256=17mwoop7YewAKQCxx4PVY8Rxa8eZkqk5TK2vDs9Xiqs,4644
3
- adafruit_circuitpython_httpserver-4.0.0.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
4
- adafruit_circuitpython_httpserver-4.0.0.dist-info/top_level.txt,sha256=N8L9ONfZQ9bILxcOPVWXOjUDA-BNLPKFir7KqAbMQbA,20
5
- adafruit_circuitpython_httpserver-4.0.0.dist-info/RECORD,,