adafruit-circuitpython-httpserver 4.5.4__py3-none-any.whl → 4.5.6__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: adafruit-circuitpython-httpserver
3
- Version: 4.5.4
3
+ Version: 4.5.6
4
4
  Summary: Simple HTTP Server for CircuitPython
5
5
  Author-email: Adafruit Industries <circuitpython@adafruit.com>
6
6
  License: MIT
@@ -0,0 +1,17 @@
1
+ adafruit_httpserver/__init__.py,sha256=kNf_uXaqR-pIqcfUNPBPeHR27wRgP4wWcCTUKOnkZ4U,1994
2
+ adafruit_httpserver/authentication.py,sha256=cNWrsPUOAAepNFJzoP3r5ODLQx-X74LkMC_1CieMq2g,2080
3
+ adafruit_httpserver/exceptions.py,sha256=tmOoUecGaSXY9kUIIV3Is5YoChrEIEJqVHl4QgmEvrg,1597
4
+ adafruit_httpserver/headers.py,sha256=KT8hzJwf97lu3cT05ptm21soPVbywmOY23qdUC3NvVs,4576
5
+ adafruit_httpserver/interfaces.py,sha256=7ByLLu1EOhF1EiaC7iqa53qPAxqiNPMZteSDC-hhtxQ,4791
6
+ adafruit_httpserver/methods.py,sha256=6SnSWDFf2oDkxsfCUt07o00FgDQyiDACrNCK_XP82eI,364
7
+ adafruit_httpserver/mime_types.py,sha256=zI2geYB7DHDK0rgpfHEJwybZXszX4lXgfCPZEyFD-mA,7149
8
+ adafruit_httpserver/request.py,sha256=67tp_QjUpV7C_KrB9qE0OxbVPAcraU3kmWK7fmjsPUs,15099
9
+ adafruit_httpserver/response.py,sha256=0-UZxj7C5k0CF2mSe3CjZrIM1bYZ4C1tWrOjH1x6XCc,28371
10
+ adafruit_httpserver/route.py,sha256=VPWcfyJ196Jd8htWM8eTZRm66Su4qVUlL8iR31Xttas,6149
11
+ adafruit_httpserver/server.py,sha256=PJH7PQ_ZDtAuXSWKjajUOKP5PPSuJJfLk1OQxPfULKo,19704
12
+ adafruit_httpserver/status.py,sha256=U3t5y3wXCYH3JUoWjta3Wd_ag05scK1njY0k-TLMBNM,1867
13
+ adafruit_circuitpython_httpserver-4.5.6.dist-info/LICENSE,sha256=gyhZwtwoqSsDGoSrV4MrLpKKWyG_jE3eROTZp1EjIUM,1102
14
+ adafruit_circuitpython_httpserver-4.5.6.dist-info/METADATA,sha256=xrSPXZDrLqTJR0OBhaytMaKHYeVgZNEe8VyQ2PTDad0,4702
15
+ adafruit_circuitpython_httpserver-4.5.6.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
16
+ adafruit_circuitpython_httpserver-4.5.6.dist-info/top_level.txt,sha256=N8L9ONfZQ9bILxcOPVWXOjUDA-BNLPKFir7KqAbMQbA,20
17
+ adafruit_circuitpython_httpserver-4.5.6.dist-info/RECORD,,
@@ -19,7 +19,7 @@ Implementation Notes
19
19
  https://github.com/adafruit/circuitpython/releases
20
20
  """
21
21
 
22
- __version__ = "4.5.4"
22
+ __version__ = "4.5.6"
23
23
  __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_HTTPServer.git"
24
24
 
25
25
 
@@ -8,11 +8,70 @@
8
8
  """
9
9
 
10
10
  try:
11
- from typing import List, Dict, Union, Any
11
+ from typing import List, Tuple, Dict, Union, Any
12
12
  except ImportError:
13
13
  pass
14
14
 
15
15
 
16
+ class _ISocket: # pylint: disable=missing-function-docstring,no-self-use,unused-argument
17
+ """A class for typing necessary methods for a socket object."""
18
+
19
+ def accept(self) -> Tuple["_ISocket", Tuple[str, int]]:
20
+ ...
21
+
22
+ def bind(self, address: Tuple[str, int]) -> None:
23
+ ...
24
+
25
+ def setblocking(self, flag: bool) -> None:
26
+ ...
27
+
28
+ def settimeout(self, value: "Union[float, None]") -> None:
29
+ ...
30
+
31
+ def setsockopt(self, level: int, optname: int, value: int) -> None:
32
+ ...
33
+
34
+ def listen(self, backlog: int) -> None:
35
+ ...
36
+
37
+ def send(self, data: bytes) -> int:
38
+ ...
39
+
40
+ def recv_into(self, buffer: memoryview, nbytes: int) -> int:
41
+ ...
42
+
43
+ def close(self) -> None:
44
+ ...
45
+
46
+
47
+ class _ISocketPool: # pylint: disable=missing-function-docstring,no-self-use,unused-argument
48
+ """A class to typing necessary methods and properties for a socket pool object."""
49
+
50
+ AF_INET: int
51
+ SO_REUSEADDR: int
52
+ SOCK_STREAM: int
53
+ SOL_SOCKET: int
54
+
55
+ def socket( # pylint: disable=redefined-builtin
56
+ self,
57
+ family: int = ...,
58
+ type: int = ...,
59
+ proto: int = ...,
60
+ ) -> _ISocket:
61
+ ...
62
+
63
+ def getaddrinfo( # pylint: disable=redefined-builtin,too-many-arguments
64
+ self,
65
+ host: str,
66
+ port: int,
67
+ family: int = ...,
68
+ type: int = ...,
69
+ proto: int = ...,
70
+ flags: int = ...,
71
+ ) -> Tuple[int, int, int, str, Tuple[str, int]]:
72
+ ...
73
+
74
+
16
75
  class _IFieldStorage:
17
76
  """Interface with shared methods for QueryParams, FormData and Headers."""
18
77
 
@@ -62,7 +121,7 @@ class _IFieldStorage:
62
121
  return key in self._storage
63
122
 
64
123
  def __repr__(self) -> str:
65
- return f"{self.__class__.__name__}({repr(self._storage)})"
124
+ return f"<{self.__class__.__name__} {repr(self._storage)}>"
66
125
 
67
126
 
68
127
  def _encode_html_entities(value: Union[str, None]) -> Union[str, None]:
@@ -9,8 +9,6 @@
9
9
 
10
10
  try:
11
11
  from typing import List, Dict, Tuple, Union, Any, TYPE_CHECKING
12
- from socket import socket
13
- from socketpool import SocketPool
14
12
 
15
13
  if TYPE_CHECKING:
16
14
  from .server import Server
@@ -20,7 +18,7 @@ except ImportError:
20
18
  import json
21
19
 
22
20
  from .headers import Headers
23
- from .interfaces import _IFieldStorage, _IXSSSafeFieldStorage
21
+ from .interfaces import _ISocket, _IFieldStorage, _IXSSSafeFieldStorage
24
22
  from .methods import POST, PUT, PATCH, DELETE
25
23
 
26
24
 
@@ -127,11 +125,11 @@ class File:
127
125
 
128
126
  def __repr__(self) -> str:
129
127
  filename, content_type, size = (
130
- repr(self.filename),
131
- repr(self.content_type),
132
- repr(self.size),
128
+ self.filename,
129
+ self.content_type,
130
+ self.size,
133
131
  )
134
- return f"{self.__class__.__name__}({filename=}, {content_type=}, {size=})"
132
+ return f"<{self.__class__.__name__} {filename=}, {content_type=}, {size=}>"
135
133
 
136
134
 
137
135
  class Files(_IFieldStorage):
@@ -260,7 +258,9 @@ class FormData(_IXSSSafeFieldStorage):
260
258
 
261
259
  def __repr__(self) -> str:
262
260
  class_name = self.__class__.__name__
263
- return f"{class_name}({repr(self._storage)}, files={repr(self.files._storage)})"
261
+ return (
262
+ f"<{class_name} {repr(self._storage)}, files={repr(self.files._storage)}>"
263
+ )
264
264
 
265
265
 
266
266
  class Request: # pylint: disable=too-many-instance-attributes
@@ -274,7 +274,7 @@ class Request: # pylint: disable=too-many-instance-attributes
274
274
  Server object that received the request.
275
275
  """
276
276
 
277
- connection: Union["SocketPool.Socket", "socket.socket"]
277
+ connection: _ISocket
278
278
  """
279
279
  Socket object used to send and receive data on the connection.
280
280
  """
@@ -325,7 +325,7 @@ class Request: # pylint: disable=too-many-instance-attributes
325
325
  def __init__(
326
326
  self,
327
327
  server: "Server",
328
- connection: Union["SocketPool.Socket", "socket.socket"],
328
+ connection: _ISocket,
329
329
  client_address: Tuple[str, int],
330
330
  raw_request: bytes = None,
331
331
  ) -> None:
@@ -481,6 +481,10 @@ class Request: # pylint: disable=too-many-instance-attributes
481
481
 
482
482
  return method, path, query_params, http_version, headers
483
483
 
484
+ def __repr__(self) -> str:
485
+ path = self.path + (f"?{self.query_params}" if self.query_params else "")
486
+ return f'<{self.__class__.__name__} "{self.method} {path}">'
487
+
484
488
 
485
489
  def _debug_unsupported_form_content_type(content_type: str) -> None:
486
490
  """Warns when an unsupported form content type is used."""
@@ -9,8 +9,6 @@
9
9
 
10
10
  try:
11
11
  from typing import Optional, Dict, Union, Tuple, Generator, Any
12
- from socket import socket
13
- from socketpool import SocketPool
14
12
  except ImportError:
15
13
  pass
16
14
 
@@ -47,6 +45,7 @@ from .status import (
47
45
  PERMANENT_REDIRECT_308,
48
46
  )
49
47
  from .headers import Headers
48
+ from .interfaces import _ISocket
50
49
 
51
50
 
52
51
  class Response: # pylint: disable=too-few-public-methods
@@ -132,7 +131,7 @@ class Response: # pylint: disable=too-few-public-methods
132
131
 
133
132
  def _send_bytes(
134
133
  self,
135
- conn: Union["SocketPool.Socket", "socket.socket"],
134
+ conn: _ISocket,
136
135
  buffer: Union[bytes, bytearray, memoryview],
137
136
  ):
138
137
  bytes_sent: int = 0
@@ -217,6 +216,10 @@ class FileResponse(Response): # pylint: disable=too-few-public-methods
217
216
  )
218
217
  self._filename = filename + "index.html" if filename.endswith("/") else filename
219
218
  self._root_path = root_path or self._request.server.root_path
219
+
220
+ if self._root_path is None:
221
+ raise ValueError("root_path must be provided in Server or in FileResponse")
222
+
220
223
  self._full_file_path = self._combine_path(self._root_path, self._filename)
221
224
  self._content_type = content_type or MIMETypes.get_for_filename(self._filename)
222
225
  self._file_length = self._get_file_length(self._full_file_path)
@@ -708,7 +711,7 @@ class Websocket(Response): # pylint: disable=too-few-public-methods
708
711
  length -= min(payload_length, length)
709
712
 
710
713
  if has_mask:
711
- payload = bytes(x ^ mask[i % 4] for i, x in enumerate(payload))
714
+ payload = bytes(byte ^ mask[idx % 4] for idx, byte in enumerate(payload))
712
715
 
713
716
  return opcode, payload
714
717
 
@@ -136,11 +136,11 @@ class Route:
136
136
  return True, dict(zip(self.parameters_names, url_parameters_values))
137
137
 
138
138
  def __repr__(self) -> str:
139
- path = repr(self.path)
140
- methods = repr(self.methods)
141
- handler = repr(self.handler)
139
+ path = self.path
140
+ methods = self.methods
141
+ handler = self.handler
142
142
 
143
- return f"Route({path=}, {methods=}, {handler=})"
143
+ return f"<Route {path=}, {methods=}, {handler=}>"
144
144
 
145
145
 
146
146
  def as_route(
@@ -8,9 +8,7 @@
8
8
  """
9
9
 
10
10
  try:
11
- from typing import Callable, Protocol, Union, List, Tuple, Dict, Iterable
12
- from socket import socket
13
- from socketpool import SocketPool
11
+ from typing import Callable, Union, List, Tuple, Dict, Iterable
14
12
  except ImportError:
15
13
  pass
16
14
 
@@ -28,6 +26,7 @@ from .exceptions import (
28
26
  ServingFilesDisabledError,
29
27
  )
30
28
  from .headers import Headers
29
+ from .interfaces import _ISocketPool, _ISocket
31
30
  from .methods import GET, HEAD
32
31
  from .request import Request
33
32
  from .response import Response, FileResponse
@@ -54,7 +53,7 @@ class Server: # pylint: disable=too-many-instance-attributes
54
53
  """Root directory to serve files from. ``None`` if serving files is disabled."""
55
54
 
56
55
  def __init__(
57
- self, socket_source: Protocol, root_path: str = None, *, debug: bool = False
56
+ self, socket_source: _ISocketPool, root_path: str = None, *, debug: bool = False
58
57
  ) -> None:
59
58
  """Create a server, and get it ready to run.
60
59
 
@@ -172,7 +171,7 @@ class Server: # pylint: disable=too-many-instance-attributes
172
171
  raise RuntimeError(f"Cannot start server on {host}:{port}") from error
173
172
 
174
173
  def serve_forever(
175
- self, host: str, port: int = 80, *, poll_interval: float = 0.1
174
+ self, host: str = "0.0.0.0", port: int = 5000, *, poll_interval: float = 0.1
176
175
  ) -> None:
177
176
  """
178
177
  Wait for HTTP requests at the given host and port. Does not return.
@@ -195,15 +194,25 @@ class Server: # pylint: disable=too-many-instance-attributes
195
194
  except Exception: # pylint: disable=broad-except
196
195
  pass # Ignore exceptions in handler function
197
196
 
198
- def _set_socket_level_to_reuse_address(self) -> None:
199
- """
200
- Only for CPython, prevents "Address already in use" error when restarting the server.
201
- """
202
- self._sock.setsockopt(
203
- self._socket_source.SOL_SOCKET, self._socket_source.SO_REUSEADDR, 1
204
- )
197
+ @staticmethod
198
+ def _create_server_socket(
199
+ socket_source: _ISocketPool,
200
+ host: str,
201
+ port: int,
202
+ ) -> _ISocket:
203
+ sock = socket_source.socket(socket_source.AF_INET, socket_source.SOCK_STREAM)
204
+
205
+ # TODO: Temporary backwards compatibility, remove after CircuitPython 9.0.0 release
206
+ if implementation.version >= (9,) or implementation.name != "circuitpython":
207
+ sock.setsockopt(socket_source.SOL_SOCKET, socket_source.SO_REUSEADDR, 1)
205
208
 
206
- def start(self, host: str, port: int = 80) -> None:
209
+ sock.bind((host, port))
210
+ sock.listen(10)
211
+ sock.setblocking(False) # Non-blocking socket
212
+
213
+ return sock
214
+
215
+ def start(self, host: str = "0.0.0.0", port: int = 5000) -> None:
207
216
  """
208
217
  Start the HTTP server at the given host and port. Requires calling
209
218
  ``.poll()`` in a while loop to handle incoming requests.
@@ -216,16 +225,7 @@ class Server: # pylint: disable=too-many-instance-attributes
216
225
  self.host, self.port = host, port
217
226
 
218
227
  self.stopped = False
219
- self._sock = self._socket_source.socket(
220
- self._socket_source.AF_INET, self._socket_source.SOCK_STREAM
221
- )
222
-
223
- if implementation.name != "circuitpython":
224
- self._set_socket_level_to_reuse_address()
225
-
226
- self._sock.bind((host, port))
227
- self._sock.listen(10)
228
- self._sock.setblocking(False) # Non-blocking socket
228
+ self._sock = self._create_server_socket(self._socket_source, host, port)
229
229
 
230
230
  if self.debug:
231
231
  _debug_started_server(self)
@@ -244,9 +244,7 @@ class Server: # pylint: disable=too-many-instance-attributes
244
244
  if self.debug:
245
245
  _debug_stopped_server(self)
246
246
 
247
- def _receive_header_bytes(
248
- self, sock: Union["SocketPool.Socket", "socket.socket"]
249
- ) -> bytes:
247
+ def _receive_header_bytes(self, sock: _ISocket) -> bytes:
250
248
  """Receive bytes until a empty line is received."""
251
249
  received_bytes = bytes()
252
250
  while b"\r\n\r\n" not in received_bytes:
@@ -263,7 +261,7 @@ class Server: # pylint: disable=too-many-instance-attributes
263
261
 
264
262
  def _receive_body_bytes(
265
263
  self,
266
- sock: Union["SocketPool.Socket", "socket.socket"],
264
+ sock: _ISocket,
267
265
  received_body_bytes: bytes,
268
266
  content_length: int,
269
267
  ) -> bytes:
@@ -282,7 +280,7 @@ class Server: # pylint: disable=too-many-instance-attributes
282
280
 
283
281
  def _receive_request(
284
282
  self,
285
- sock: Union["SocketPool.Socket", "socket.socket"],
283
+ sock: _ISocket,
286
284
  client_address: Tuple[str, int],
287
285
  ) -> Request:
288
286
  """Receive bytes from socket until the whole request is received."""
@@ -399,6 +397,7 @@ class Server: # pylint: disable=too-many-instance-attributes
399
397
  if self.stopped:
400
398
  raise ServerStoppedError
401
399
 
400
+ conn = None
402
401
  try:
403
402
  conn, client_address = self._sock.accept()
404
403
  conn.settimeout(self._timeout)
@@ -444,7 +443,8 @@ class Server: # pylint: disable=too-many-instance-attributes
444
443
  if self.debug:
445
444
  _debug_exception_in_handler(error)
446
445
 
447
- conn.close()
446
+ if conn is not None:
447
+ conn.close()
448
448
  raise error # Raise the exception again to be handled by the user.
449
449
 
450
450
  def require_authentication(self, auths: List[Union[Basic, Token, Bearer]]) -> None:
@@ -528,6 +528,13 @@ class Server: # pylint: disable=too-many-instance-attributes
528
528
  else:
529
529
  raise ValueError("Server.socket_timeout must be a positive numeric value.")
530
530
 
531
+ def __repr__(self) -> str:
532
+ host = self.host
533
+ port = self.port
534
+ root_path = self.root_path
535
+
536
+ return f"<Server {host=}, {port=}, {root_path=}>"
537
+
531
538
 
532
539
  def _debug_warning_exposed_files(root_path: str):
533
540
  """Warns about exposing all files on the device."""
@@ -21,14 +21,17 @@ class Status: # pylint: disable=too-few-public-methods
21
21
  self.code = code
22
22
  self.text = text
23
23
 
24
- def __repr__(self):
25
- return f'Status({self.code}, "{self.text}")'
24
+ def __eq__(self, other: "Status"):
25
+ return self.code == other.code and self.text == other.text
26
26
 
27
27
  def __str__(self):
28
28
  return f"{self.code} {self.text}"
29
29
 
30
- def __eq__(self, other: "Status"):
31
- return self.code == other.code and self.text == other.text
30
+ def __repr__(self):
31
+ code = self.code
32
+ text = self.text
33
+
34
+ return f'<Status {code}, "{text}">'
32
35
 
33
36
 
34
37
  SWITCHING_PROTOCOLS_101 = Status(101, "Switching Protocols")
@@ -1,17 +0,0 @@
1
- adafruit_httpserver/__init__.py,sha256=D6jQH8bfQsUFV4ZreK612ADoNoPZ-WPBWPSk5w_ITmk,1994
2
- adafruit_httpserver/authentication.py,sha256=cNWrsPUOAAepNFJzoP3r5ODLQx-X74LkMC_1CieMq2g,2080
3
- adafruit_httpserver/exceptions.py,sha256=tmOoUecGaSXY9kUIIV3Is5YoChrEIEJqVHl4QgmEvrg,1597
4
- adafruit_httpserver/headers.py,sha256=KT8hzJwf97lu3cT05ptm21soPVbywmOY23qdUC3NvVs,4576
5
- adafruit_httpserver/interfaces.py,sha256=4r0AoVXf6GqcEejkw7m9Yd9tmZAOr1TXAa5u2H5O714,3292
6
- adafruit_httpserver/methods.py,sha256=6SnSWDFf2oDkxsfCUt07o00FgDQyiDACrNCK_XP82eI,364
7
- adafruit_httpserver/mime_types.py,sha256=zI2geYB7DHDK0rgpfHEJwybZXszX4lXgfCPZEyFD-mA,7149
8
- adafruit_httpserver/request.py,sha256=dtRMkllCO8VRvI6v6eL8LEA-oGu_SB7kBVCRZCjdMeM,15036
9
- adafruit_httpserver/response.py,sha256=jiEqyDAAixOXMA-U89lUuaFd4FiTm0r0u7vAlEvODXI,28305
10
- adafruit_httpserver/route.py,sha256=09asPOs8GxyutYPELWwppY-X49AzhEOfR-L8VVrBKVg,6166
11
- adafruit_httpserver/server.py,sha256=U7OOMQdHnAn8lJaQ_llnjmCHR0Ta2Eh3fM08tWnE0uo,19548
12
- adafruit_httpserver/status.py,sha256=x6QNFagXgold9ebWWxghwvIsyQORKseFA9k0ySaXptc,1825
13
- adafruit_circuitpython_httpserver-4.5.4.dist-info/LICENSE,sha256=gyhZwtwoqSsDGoSrV4MrLpKKWyG_jE3eROTZp1EjIUM,1102
14
- adafruit_circuitpython_httpserver-4.5.4.dist-info/METADATA,sha256=YYkt7alylkBPSwCDp8EkVg47PaovpjTSq26K1YVjBxs,4702
15
- adafruit_circuitpython_httpserver-4.5.4.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
16
- adafruit_circuitpython_httpserver-4.5.4.dist-info/top_level.txt,sha256=N8L9ONfZQ9bILxcOPVWXOjUDA-BNLPKFir7KqAbMQbA,20
17
- adafruit_circuitpython_httpserver-4.5.4.dist-info/RECORD,,