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.
- {adafruit_circuitpython_httpserver-4.0.1.dist-info → adafruit_circuitpython_httpserver-4.0.2.dist-info}/METADATA +1 -1
- adafruit_circuitpython_httpserver-4.0.2.dist-info/RECORD +16 -0
- adafruit_httpserver/__init__.py +81 -0
- adafruit_httpserver/authentication.py +64 -0
- adafruit_httpserver/exceptions.py +64 -0
- adafruit_httpserver/headers.py +104 -0
- adafruit_httpserver/methods.py +27 -0
- adafruit_httpserver/mime_types.py +207 -0
- adafruit_httpserver/request.py +172 -0
- adafruit_httpserver/response.py +393 -0
- adafruit_httpserver/route.py +159 -0
- adafruit_httpserver/server.py +453 -0
- adafruit_httpserver/status.py +64 -0
- adafruit_circuitpython_httpserver-4.0.1.dist-info/RECORD +0 -5
- {adafruit_circuitpython_httpserver-4.0.1.dist-info → adafruit_circuitpython_httpserver-4.0.2.dist-info}/LICENSE +0 -0
- {adafruit_circuitpython_httpserver-4.0.1.dist-info → adafruit_circuitpython_httpserver-4.0.2.dist-info}/WHEEL +0 -0
- {adafruit_circuitpython_httpserver-4.0.1.dist-info → adafruit_circuitpython_httpserver-4.0.2.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
adafruit_httpserver/__init__.py,sha256=kC4iIDt9Se2_oo7VPYC5JR1BywCxd71yIEgOPCfU1-c,1687
|
|
2
|
+
adafruit_httpserver/authentication.py,sha256=YJFucBOms37RiqIILnL0cxMMgxXrUzYtcQhnXF55MMY,1725
|
|
3
|
+
adafruit_httpserver/exceptions.py,sha256=ZVf_EyP7Hw_PGCxmoTQo4xLwxsUd1PiUwA1kpH-C8do,1618
|
|
4
|
+
adafruit_httpserver/headers.py,sha256=VCPI2vWmTsgbgqHabByckGFSp5SO1pB28JSIrQFVVvc,2914
|
|
5
|
+
adafruit_httpserver/methods.py,sha256=iUIuULpjoAgxpRttGLvbj-dWaphveNbG_q0bnk603wk,385
|
|
6
|
+
adafruit_httpserver/mime_types.py,sha256=oEVvvv4nf2mesfVMiBUtUj4A0oCI4SUJFxF3IRAYRl0,7133
|
|
7
|
+
adafruit_httpserver/request.py,sha256=OiUqb8gTAj1qKI1b4bvxDT8XvBYP_B2IpG_Y_iw-oqw,4632
|
|
8
|
+
adafruit_httpserver/response.py,sha256=s7aviUKpFSUqw6eOMHEbOjvrPrRQGrOttjnu_58AVlo,13347
|
|
9
|
+
adafruit_httpserver/route.py,sha256=rmRdj54a0XBBH6wzbFxsKwYeNrDKl_JgLKrHTPCgKHo,4736
|
|
10
|
+
adafruit_httpserver/server.py,sha256=-B3PNlvig1KlT3ulC1KiKLuZ0B6bFvhlnLjULdtQVow,15414
|
|
11
|
+
adafruit_httpserver/status.py,sha256=cuK1_qwTeunG-oMIO56LABs8CiPa-36yciiANq2Clow,1655
|
|
12
|
+
adafruit_circuitpython_httpserver-4.0.2.dist-info/LICENSE,sha256=gyhZwtwoqSsDGoSrV4MrLpKKWyG_jE3eROTZp1EjIUM,1102
|
|
13
|
+
adafruit_circuitpython_httpserver-4.0.2.dist-info/METADATA,sha256=w-IGDcgZVlSdhLZbRgMFw-T31D_bV9AZG5FNemh69lE,4644
|
|
14
|
+
adafruit_circuitpython_httpserver-4.0.2.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
|
|
15
|
+
adafruit_circuitpython_httpserver-4.0.2.dist-info/top_level.txt,sha256=N8L9ONfZQ9bILxcOPVWXOjUDA-BNLPKFir7KqAbMQbA,20
|
|
16
|
+
adafruit_circuitpython_httpserver-4.0.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""
|
|
5
|
+
`adafruit_httpserver`
|
|
6
|
+
================================================================================
|
|
7
|
+
|
|
8
|
+
Socket based HTTP Server for CircuitPython
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
* Author(s): Dan Halbert, Michał Pokusa
|
|
12
|
+
|
|
13
|
+
Implementation Notes
|
|
14
|
+
--------------------
|
|
15
|
+
|
|
16
|
+
**Software and Dependencies:**
|
|
17
|
+
|
|
18
|
+
* Adafruit CircuitPython firmware for the supported boards:
|
|
19
|
+
https://github.com/adafruit/circuitpython/releases
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
__version__ = "4.0.2"
|
|
23
|
+
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_HTTPServer.git"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
from .authentication import (
|
|
27
|
+
Basic,
|
|
28
|
+
Bearer,
|
|
29
|
+
check_authentication,
|
|
30
|
+
require_authentication,
|
|
31
|
+
)
|
|
32
|
+
from .exceptions import (
|
|
33
|
+
ServerStoppedError,
|
|
34
|
+
AuthenticationError,
|
|
35
|
+
InvalidPathError,
|
|
36
|
+
ParentDirectoryReferenceError,
|
|
37
|
+
BackslashInPathError,
|
|
38
|
+
ServingFilesDisabledError,
|
|
39
|
+
FileNotExistsError,
|
|
40
|
+
)
|
|
41
|
+
from .headers import Headers
|
|
42
|
+
from .methods import (
|
|
43
|
+
GET,
|
|
44
|
+
POST,
|
|
45
|
+
PUT,
|
|
46
|
+
DELETE,
|
|
47
|
+
PATCH,
|
|
48
|
+
HEAD,
|
|
49
|
+
OPTIONS,
|
|
50
|
+
TRACE,
|
|
51
|
+
CONNECT,
|
|
52
|
+
)
|
|
53
|
+
from .mime_types import MIMETypes
|
|
54
|
+
from .request import Request
|
|
55
|
+
from .response import (
|
|
56
|
+
Response,
|
|
57
|
+
FileResponse,
|
|
58
|
+
ChunkedResponse,
|
|
59
|
+
JSONResponse,
|
|
60
|
+
Redirect,
|
|
61
|
+
)
|
|
62
|
+
from .server import Server
|
|
63
|
+
from .status import (
|
|
64
|
+
Status,
|
|
65
|
+
OK_200,
|
|
66
|
+
CREATED_201,
|
|
67
|
+
ACCEPTED_202,
|
|
68
|
+
NO_CONTENT_204,
|
|
69
|
+
PARTIAL_CONTENT_206,
|
|
70
|
+
TEMPORARY_REDIRECT_307,
|
|
71
|
+
PERMANENT_REDIRECT_308,
|
|
72
|
+
BAD_REQUEST_400,
|
|
73
|
+
UNAUTHORIZED_401,
|
|
74
|
+
FORBIDDEN_403,
|
|
75
|
+
NOT_FOUND_404,
|
|
76
|
+
METHOD_NOT_ALLOWED_405,
|
|
77
|
+
TOO_MANY_REQUESTS_429,
|
|
78
|
+
INTERNAL_SERVER_ERROR_500,
|
|
79
|
+
NOT_IMPLEMENTED_501,
|
|
80
|
+
SERVICE_UNAVAILABLE_503,
|
|
81
|
+
)
|
|
@@ -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.authentication`
|
|
6
|
+
====================================================
|
|
7
|
+
* Author(s): Michał Pokusa
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
from typing import Union, List
|
|
12
|
+
except ImportError:
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
from binascii import b2a_base64
|
|
16
|
+
|
|
17
|
+
from .exceptions import AuthenticationError
|
|
18
|
+
from .request import Request
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Basic:
|
|
22
|
+
"""Represents HTTP Basic Authentication."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, username: str, password: str) -> None:
|
|
25
|
+
self._value = b2a_base64(f"{username}:{password}".encode()).decode().strip()
|
|
26
|
+
|
|
27
|
+
def __str__(self) -> str:
|
|
28
|
+
return f"Basic {self._value}"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Bearer:
|
|
32
|
+
"""Represents HTTP Bearer Token Authentication."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, token: str) -> None:
|
|
35
|
+
self._value = token
|
|
36
|
+
|
|
37
|
+
def __str__(self) -> str:
|
|
38
|
+
return f"Bearer {self._value}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def check_authentication(request: Request, auths: List[Union[Basic, Bearer]]) -> bool:
|
|
42
|
+
"""
|
|
43
|
+
Returns ``True`` if request is authorized by any of the authentications, ``False`` otherwise.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
auth_header = request.headers.get("Authorization")
|
|
47
|
+
|
|
48
|
+
if auth_header is None:
|
|
49
|
+
return False
|
|
50
|
+
|
|
51
|
+
return any(auth_header == str(auth) for auth in auths)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def require_authentication(request: Request, auths: List[Union[Basic, Bearer]]) -> None:
|
|
55
|
+
"""
|
|
56
|
+
Checks if the request is authorized and raises ``AuthenticationError`` if not.
|
|
57
|
+
|
|
58
|
+
If the error is not caught, the server will return ``401 Unauthorized``.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
if not check_authentication(request, auths):
|
|
62
|
+
raise AuthenticationError(
|
|
63
|
+
"Request is not authenticated by any of the provided authentications"
|
|
64
|
+
)
|
|
@@ -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.exceptions`
|
|
6
|
+
====================================================
|
|
7
|
+
* Author(s): Michał Pokusa
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ServerStoppedError(Exception):
|
|
12
|
+
"""
|
|
13
|
+
Raised when ``.poll`` is called on a stopped ``Server``.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AuthenticationError(Exception):
|
|
18
|
+
"""
|
|
19
|
+
Raised by ``require_authentication`` when the ``Request`` is not authorized.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class InvalidPathError(Exception):
|
|
24
|
+
"""
|
|
25
|
+
Parent class for all path related errors.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ParentDirectoryReferenceError(InvalidPathError):
|
|
30
|
+
"""
|
|
31
|
+
Path contains ``..``, a reference to the parent directory.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, path: str) -> None:
|
|
35
|
+
"""Creates a new ``ParentDirectoryReferenceError`` for the ``path``."""
|
|
36
|
+
super().__init__(f"Parent directory reference in path: {path}")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class BackslashInPathError(InvalidPathError):
|
|
40
|
+
"""
|
|
41
|
+
Backslash ``\\`` in path.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(self, path: str) -> None:
|
|
45
|
+
"""Creates a new ``BackslashInPathError`` for the ``path``."""
|
|
46
|
+
super().__init__(f"Backslash in path: {path}")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ServingFilesDisabledError(Exception):
|
|
50
|
+
"""
|
|
51
|
+
Raised when ``root_path`` is not set and there is no handler for ``request``.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class FileNotExistsError(Exception):
|
|
56
|
+
"""
|
|
57
|
+
Raised when a file does not exist.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, path: str) -> None:
|
|
61
|
+
"""
|
|
62
|
+
Creates a new ``FileNotExistsError`` for the file at ``path``.
|
|
63
|
+
"""
|
|
64
|
+
super().__init__(f"File does not exist: {path}")
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""
|
|
5
|
+
`adafruit_httpserver.headers`
|
|
6
|
+
====================================================
|
|
7
|
+
* Author(s): Michał Pokusa
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
from typing import Dict, Tuple
|
|
12
|
+
except ImportError:
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Headers:
|
|
17
|
+
"""
|
|
18
|
+
A dict-like class for storing HTTP headers.
|
|
19
|
+
|
|
20
|
+
Allows access to headers using **case insensitive** names.
|
|
21
|
+
|
|
22
|
+
Does **not** implement all dict methods.
|
|
23
|
+
|
|
24
|
+
Examples::
|
|
25
|
+
|
|
26
|
+
headers = Headers({"Content-Type": "text/html", "Content-Length": "1024"})
|
|
27
|
+
|
|
28
|
+
len(headers)
|
|
29
|
+
# 2
|
|
30
|
+
|
|
31
|
+
headers.setdefault("Access-Control-Allow-Origin", "*")
|
|
32
|
+
headers["Access-Control-Allow-Origin"]
|
|
33
|
+
# '*'
|
|
34
|
+
|
|
35
|
+
headers["Content-Length"]
|
|
36
|
+
# '1024'
|
|
37
|
+
|
|
38
|
+
headers["content-type"]
|
|
39
|
+
# 'text/html'
|
|
40
|
+
|
|
41
|
+
headers["User-Agent"]
|
|
42
|
+
# KeyError: User-Agent
|
|
43
|
+
|
|
44
|
+
"CONTENT-TYPE" in headers
|
|
45
|
+
# True
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
_storage: Dict[str, Tuple[str, str]]
|
|
49
|
+
|
|
50
|
+
def __init__(self, headers: Dict[str, str] = None) -> None:
|
|
51
|
+
headers = headers or {}
|
|
52
|
+
|
|
53
|
+
self._storage = {key.lower(): [key, value] for key, value in headers.items()}
|
|
54
|
+
|
|
55
|
+
def get(self, name: str, default: str = None):
|
|
56
|
+
"""Returns the value for the given header name, or default if not found."""
|
|
57
|
+
return self._storage.get(name.lower(), [None, default])[1]
|
|
58
|
+
|
|
59
|
+
def setdefault(self, name: str, default: str = None):
|
|
60
|
+
"""Sets the value for the given header name if it does not exist."""
|
|
61
|
+
return self._storage.setdefault(name.lower(), [name, default])[1]
|
|
62
|
+
|
|
63
|
+
def items(self):
|
|
64
|
+
"""Returns a list of (name, value) tuples."""
|
|
65
|
+
return dict(self._storage.values()).items()
|
|
66
|
+
|
|
67
|
+
def keys(self):
|
|
68
|
+
"""Returns a list of header names."""
|
|
69
|
+
return dict(self._storage.values()).keys()
|
|
70
|
+
|
|
71
|
+
def values(self):
|
|
72
|
+
"""Returns a list of header values."""
|
|
73
|
+
return dict(self._storage.values()).values()
|
|
74
|
+
|
|
75
|
+
def update(self, headers: Dict[str, str]):
|
|
76
|
+
"""Updates the headers with the given dict."""
|
|
77
|
+
return self._storage.update(
|
|
78
|
+
{key.lower(): [key, value] for key, value in headers.items()}
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
def copy(self):
|
|
82
|
+
"""Returns a copy of the headers."""
|
|
83
|
+
return Headers(dict(self._storage.values()))
|
|
84
|
+
|
|
85
|
+
def __getitem__(self, name: str):
|
|
86
|
+
return self._storage[name.lower()][1]
|
|
87
|
+
|
|
88
|
+
def __setitem__(self, name: str, value: str):
|
|
89
|
+
self._storage[name.lower()] = [name, value]
|
|
90
|
+
|
|
91
|
+
def __delitem__(self, name: str):
|
|
92
|
+
del self._storage[name.lower()]
|
|
93
|
+
|
|
94
|
+
def __iter__(self):
|
|
95
|
+
return iter(dict(self._storage.values()))
|
|
96
|
+
|
|
97
|
+
def __len__(self):
|
|
98
|
+
return len(self._storage)
|
|
99
|
+
|
|
100
|
+
def __contains__(self, key: str):
|
|
101
|
+
return key.lower() in self._storage.keys()
|
|
102
|
+
|
|
103
|
+
def __repr__(self):
|
|
104
|
+
return f"{self.__class__.__name__}({dict(self._storage.values())})"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""
|
|
5
|
+
`adafruit_httpserver.methods`
|
|
6
|
+
====================================================
|
|
7
|
+
* Author(s): Michał Pokusa
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
GET = "GET"
|
|
12
|
+
|
|
13
|
+
POST = "POST"
|
|
14
|
+
|
|
15
|
+
PUT = "PUT"
|
|
16
|
+
|
|
17
|
+
DELETE = "DELETE"
|
|
18
|
+
|
|
19
|
+
PATCH = "PATCH"
|
|
20
|
+
|
|
21
|
+
HEAD = "HEAD"
|
|
22
|
+
|
|
23
|
+
OPTIONS = "OPTIONS"
|
|
24
|
+
|
|
25
|
+
TRACE = "TRACE"
|
|
26
|
+
|
|
27
|
+
CONNECT = "CONNECT"
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""
|
|
5
|
+
`adafruit_httpserver.mime_types`
|
|
6
|
+
====================================================
|
|
7
|
+
* Author(s): Michał Pokusa
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
from typing import List, Dict
|
|
12
|
+
except ImportError:
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class MIMETypes:
|
|
17
|
+
"""
|
|
18
|
+
Contains MIME types for common file extensions.
|
|
19
|
+
Allows to set default type for unknown files, unregister unused types and register new ones
|
|
20
|
+
using the ``MIMETypes.configure()``.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
DEFAULT = "text/plain"
|
|
24
|
+
"""
|
|
25
|
+
Default MIME type for unknown files.
|
|
26
|
+
Can be changed using ``MIMETypes.configure(default_to=...)``.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
REGISTERED = {
|
|
30
|
+
".7z": "application/x-7z-compressed",
|
|
31
|
+
".aac": "audio/aac",
|
|
32
|
+
".abw": "application/x-abiword",
|
|
33
|
+
".arc": "application/x-freearc",
|
|
34
|
+
".avi": "video/x-msvideo",
|
|
35
|
+
".azw": "application/vnd.amazon.ebook",
|
|
36
|
+
".bin": "application/octet-stream",
|
|
37
|
+
".bmp": "image/bmp",
|
|
38
|
+
".bz": "application/x-bzip",
|
|
39
|
+
".bz2": "application/x-bzip2",
|
|
40
|
+
".cda": "application/x-cdf",
|
|
41
|
+
".csh": "application/x-csh",
|
|
42
|
+
".css": "text/css",
|
|
43
|
+
".csv": "text/csv",
|
|
44
|
+
".doc": "application/msword",
|
|
45
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
46
|
+
".eot": "application/vnd.ms-fontobject",
|
|
47
|
+
".epub": "application/epub+zip",
|
|
48
|
+
".gif": "image/gif",
|
|
49
|
+
".gz": "application/gzip",
|
|
50
|
+
".htm": "text/html",
|
|
51
|
+
".html": "text/html",
|
|
52
|
+
".ico": "image/vnd.microsoft.icon",
|
|
53
|
+
".ics": "text/calendar",
|
|
54
|
+
".jar": "application/java-archive",
|
|
55
|
+
".jpeg": "image/jpeg",
|
|
56
|
+
".jpg": "image/jpeg",
|
|
57
|
+
".js": "text/javascript",
|
|
58
|
+
".json": "application/json",
|
|
59
|
+
".jsonld": "application/ld+json",
|
|
60
|
+
".mid": "audio/midi",
|
|
61
|
+
".midi": "audio/midi",
|
|
62
|
+
".mjs": "text/javascript",
|
|
63
|
+
".mp3": "audio/mpeg",
|
|
64
|
+
".mp4": "video/mp4",
|
|
65
|
+
".mpeg": "video/mpeg",
|
|
66
|
+
".mpkg": "application/vnd.apple.installer+xml",
|
|
67
|
+
".odp": "application/vnd.oasis.opendocument.presentation",
|
|
68
|
+
".ods": "application/vnd.oasis.opendocument.spreadsheet",
|
|
69
|
+
".odt": "application/vnd.oasis.opendocument.text",
|
|
70
|
+
".oga": "audio/ogg",
|
|
71
|
+
".ogv": "video/ogg",
|
|
72
|
+
".ogx": "application/ogg",
|
|
73
|
+
".opus": "audio/opus",
|
|
74
|
+
".otf": "font/otf",
|
|
75
|
+
".pdf": "application/pdf",
|
|
76
|
+
".php": "application/x-httpd-php",
|
|
77
|
+
".png": "image/png",
|
|
78
|
+
".ppt": "application/vnd.ms-powerpoint",
|
|
79
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
80
|
+
".rar": "application/vnd.rar",
|
|
81
|
+
".rtf": "application/rtf",
|
|
82
|
+
".sh": "application/x-sh",
|
|
83
|
+
".svg": "image/svg+xml",
|
|
84
|
+
".swf": "application/x-shockwave-flash",
|
|
85
|
+
".tar": "application/x-tar",
|
|
86
|
+
".tif": "image/tiff",
|
|
87
|
+
".tiff": "image/tiff",
|
|
88
|
+
".ts": "video/mp2t",
|
|
89
|
+
".ttf": "font/ttf",
|
|
90
|
+
".txt": "text/plain",
|
|
91
|
+
".vsd": "application/vnd.visio",
|
|
92
|
+
".wav": "audio/wav",
|
|
93
|
+
".weba": "audio/webm",
|
|
94
|
+
".webm": "video/webm",
|
|
95
|
+
".webp": "image/webp",
|
|
96
|
+
".woff": "font/woff",
|
|
97
|
+
".woff2": "font/woff2",
|
|
98
|
+
".xhtml": "application/xhtml+xml",
|
|
99
|
+
".xls": "application/vnd.ms-excel",
|
|
100
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
101
|
+
".xml": "application/xml",
|
|
102
|
+
".xul": "application/vnd.mozilla.xul+xml",
|
|
103
|
+
".zip": "application/zip",
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def __check_all_start_with_dot(extensions: List[str]) -> None:
|
|
108
|
+
for extension in extensions:
|
|
109
|
+
if not extension.startswith("."):
|
|
110
|
+
raise ValueError(
|
|
111
|
+
f'Invalid extension: "{extension}". All extensions must start with a dot.'
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def __check_all_are_registered(cls, extensions: List[str]) -> None:
|
|
116
|
+
registered_extensions = cls.REGISTERED.keys()
|
|
117
|
+
|
|
118
|
+
for extension in extensions:
|
|
119
|
+
if not extension in registered_extensions:
|
|
120
|
+
raise ValueError(f'Extension "{extension}" is not registered. ')
|
|
121
|
+
|
|
122
|
+
@classmethod
|
|
123
|
+
def _default_to(cls, mime_type: str) -> None:
|
|
124
|
+
"""
|
|
125
|
+
Set the default MIME type for unknown files.
|
|
126
|
+
|
|
127
|
+
:param str mime_type: The MIME type to use for unknown files.
|
|
128
|
+
"""
|
|
129
|
+
cls.DEFAULT = mime_type
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
def _keep_for(cls, extensions: List[str]) -> None:
|
|
133
|
+
"""
|
|
134
|
+
Unregisters all MIME types except the ones for the given extensions,\
|
|
135
|
+
**decreasing overall memory usage**.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
cls.__check_all_start_with_dot(extensions)
|
|
139
|
+
cls.__check_all_are_registered(extensions)
|
|
140
|
+
|
|
141
|
+
current_extensions = iter(cls.REGISTERED.keys())
|
|
142
|
+
|
|
143
|
+
cls.REGISTERED = {
|
|
144
|
+
extension: cls.REGISTERED[extension]
|
|
145
|
+
for extension in current_extensions
|
|
146
|
+
if extension in extensions
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
@classmethod
|
|
150
|
+
def _register(cls, mime_types: dict) -> None:
|
|
151
|
+
"""
|
|
152
|
+
Register multiple MIME types.
|
|
153
|
+
|
|
154
|
+
:param dict mime_types: A dictionary mapping file extensions to MIME types.
|
|
155
|
+
"""
|
|
156
|
+
cls.__check_all_start_with_dot(mime_types.keys())
|
|
157
|
+
cls.REGISTERED.update(mime_types)
|
|
158
|
+
|
|
159
|
+
@classmethod
|
|
160
|
+
def configure(
|
|
161
|
+
cls,
|
|
162
|
+
default_to: str = None,
|
|
163
|
+
keep_for: List[str] = None,
|
|
164
|
+
register: Dict[str, str] = None,
|
|
165
|
+
) -> None:
|
|
166
|
+
"""
|
|
167
|
+
Allows to globally configure the MIME types.
|
|
168
|
+
|
|
169
|
+
It is recommended to **always** call this method before starting the ``Server``.
|
|
170
|
+
Unregistering unused MIME types will **decrease overall memory usage**.
|
|
171
|
+
|
|
172
|
+
:param str default_to: The MIME type to use for unknown files.
|
|
173
|
+
:param List[str] keep_for: File extensions to keep. All other will be unregistered.
|
|
174
|
+
:param Dict[str, str] register: A dictionary mapping file extensions to MIME types.
|
|
175
|
+
|
|
176
|
+
Example::
|
|
177
|
+
|
|
178
|
+
MIMETypes.configure(
|
|
179
|
+
default_to="text/plain",
|
|
180
|
+
keep_for=[".jpg", ".mp4", ".txt"],
|
|
181
|
+
register={".foo": "text/foo", ".bar": "text/bar", ".baz": "text/baz"},
|
|
182
|
+
)
|
|
183
|
+
"""
|
|
184
|
+
if default_to is not None:
|
|
185
|
+
cls._default_to(default_to)
|
|
186
|
+
if keep_for is not None:
|
|
187
|
+
cls._keep_for(keep_for)
|
|
188
|
+
if register is not None:
|
|
189
|
+
cls._register(register)
|
|
190
|
+
|
|
191
|
+
@classmethod
|
|
192
|
+
def get_for_filename(cls, filename: str, default: str = None) -> str:
|
|
193
|
+
"""
|
|
194
|
+
Return the MIME type for the given file name.
|
|
195
|
+
If the file extension is not registered, ``default`` is returned.
|
|
196
|
+
|
|
197
|
+
:param str filename: The file name to look up.
|
|
198
|
+
:param str default: Default MIME type to return if the file extension is not registered.
|
|
199
|
+
"""
|
|
200
|
+
if default is None:
|
|
201
|
+
default = cls.DEFAULT
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
extension = filename.rsplit(".", 1)[-1].lower()
|
|
205
|
+
return cls.REGISTERED.get(f".{extension}", default)
|
|
206
|
+
except IndexError:
|
|
207
|
+
return default
|