rapis 0.0.1__tar.gz
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.
- rapis-0.0.1/PKG-INFO +58 -0
- rapis-0.0.1/README.md +49 -0
- rapis-0.0.1/pyproject.toml +93 -0
- rapis-0.0.1/rapis.egg-info/PKG-INFO +58 -0
- rapis-0.0.1/rapis.egg-info/SOURCES.txt +18 -0
- rapis-0.0.1/rapis.egg-info/dependency_links.txt +1 -0
- rapis-0.0.1/rapis.egg-info/requires.txt +2 -0
- rapis-0.0.1/rapis.egg-info/top_level.txt +1 -0
- rapis-0.0.1/setup.cfg +4 -0
- rapis-0.0.1/src/__init__.py +6 -0
- rapis-0.0.1/src/_application.py +35 -0
- rapis-0.0.1/src/_handler.py +133 -0
- rapis-0.0.1/src/_middleware.py +33 -0
- rapis-0.0.1/src/_params.py +7 -0
- rapis-0.0.1/src/_path_pattern.py +57 -0
- rapis-0.0.1/src/_request.py +0 -0
- rapis-0.0.1/src/_response.py +0 -0
- rapis-0.0.1/src/_route.py +101 -0
- rapis-0.0.1/src/_router.py +104 -0
- rapis-0.0.1/src/_types.py +11 -0
rapis-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rapis
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
Requires-Python: >=3.14
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: granian>=2.7.4
|
|
8
|
+
Requires-Dist: msgspec>=0.21.1
|
|
9
|
+
|
|
10
|
+
# Rapis - Minimalistic web library
|
|
11
|
+
|
|
12
|
+
this library was inspired by FastAPI so syntax may be identical
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from rapis import AppRouter, WebApp
|
|
16
|
+
|
|
17
|
+
app = WebApp()
|
|
18
|
+
router = AppRouter()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@router.get("/")
|
|
22
|
+
async def root() -> dict:
|
|
23
|
+
return {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
app.include_router(router)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
### ! WARNING: Library in early development, it is NOT READY for production
|
|
32
|
+
|
|
33
|
+
### from Pypi
|
|
34
|
+
|
|
35
|
+
#### WIP
|
|
36
|
+
|
|
37
|
+
### from source
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
git clone https://github.com/sheptalo/rapis folder
|
|
41
|
+
pip install ./folder
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## DOCS will be implemented soon
|
|
45
|
+
|
|
46
|
+
## TODO
|
|
47
|
+
|
|
48
|
+
- [ ] Exception handling
|
|
49
|
+
- [ ] Request/Response Work model
|
|
50
|
+
- [ ] Docs
|
|
51
|
+
- [ ] More availabilities to expand logic
|
|
52
|
+
- [ ] better Query params handle
|
|
53
|
+
- [ ] chage routing from linear to something else
|
|
54
|
+
- [ ] rewrite path patterns logic
|
|
55
|
+
- [ ] review Middleware logic (it was taked from fastapi)
|
|
56
|
+
- [ ] websocket support(maybe)
|
|
57
|
+
- [ ] coverage
|
|
58
|
+
- [ ] typing support (for now a few Errors in mypy, maybe start using TY)
|
rapis-0.0.1/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Rapis - Minimalistic web library
|
|
2
|
+
|
|
3
|
+
this library was inspired by FastAPI so syntax may be identical
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from rapis import AppRouter, WebApp
|
|
7
|
+
|
|
8
|
+
app = WebApp()
|
|
9
|
+
router = AppRouter()
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@router.get("/")
|
|
13
|
+
async def root() -> dict:
|
|
14
|
+
return {}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
app.include_router(router)
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
### ! WARNING: Library in early development, it is NOT READY for production
|
|
23
|
+
|
|
24
|
+
### from Pypi
|
|
25
|
+
|
|
26
|
+
#### WIP
|
|
27
|
+
|
|
28
|
+
### from source
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
git clone https://github.com/sheptalo/rapis folder
|
|
32
|
+
pip install ./folder
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## DOCS will be implemented soon
|
|
36
|
+
|
|
37
|
+
## TODO
|
|
38
|
+
|
|
39
|
+
- [ ] Exception handling
|
|
40
|
+
- [ ] Request/Response Work model
|
|
41
|
+
- [ ] Docs
|
|
42
|
+
- [ ] More availabilities to expand logic
|
|
43
|
+
- [ ] better Query params handle
|
|
44
|
+
- [ ] chage routing from linear to something else
|
|
45
|
+
- [ ] rewrite path patterns logic
|
|
46
|
+
- [ ] review Middleware logic (it was taked from fastapi)
|
|
47
|
+
- [ ] websocket support(maybe)
|
|
48
|
+
- [ ] coverage
|
|
49
|
+
- [ ] typing support (for now a few Errors in mypy, maybe start using TY)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.2"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "rapis"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "Add your description here"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.14"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"granian>=2.7.4",
|
|
13
|
+
"msgspec>=0.21.1",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[tool.setuptools]
|
|
17
|
+
package-dir = {"rapis" = "src"}
|
|
18
|
+
packages = ["rapis"]
|
|
19
|
+
|
|
20
|
+
[dependency-groups]
|
|
21
|
+
dev = [
|
|
22
|
+
"mypy>=1.20.2",
|
|
23
|
+
"ruff>=0.15.12",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
[tool.ruff]
|
|
28
|
+
exclude = [
|
|
29
|
+
".bzr", ".direnv", ".eggs", ".git", ".git-rewrite", ".hg", ".ipynb_checkpoints",
|
|
30
|
+
".mypy_cache", ".nox", ".pants.d", ".pyenv", ".pytest_cache", ".pytype", ".ruff_cache",
|
|
31
|
+
".svn", ".tox", ".venv", ".vscode", "__pypackages__", "_build", "buck-out",
|
|
32
|
+
"build", "dist", "node_modules", "site-packages", "venv",
|
|
33
|
+
]
|
|
34
|
+
line-length = 79
|
|
35
|
+
indent-width = 4
|
|
36
|
+
target-version = "py314"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
[tool.ruff.format]
|
|
40
|
+
quote-style = "double"
|
|
41
|
+
indent-style = "space"
|
|
42
|
+
skip-magic-trailing-comma = false
|
|
43
|
+
line-ending = "auto"
|
|
44
|
+
docstring-code-format = false
|
|
45
|
+
|
|
46
|
+
[tool.ruff.lint]
|
|
47
|
+
select = [
|
|
48
|
+
"A",
|
|
49
|
+
"B",
|
|
50
|
+
"BLE",
|
|
51
|
+
"E",
|
|
52
|
+
"F",
|
|
53
|
+
"FURB",
|
|
54
|
+
"G",
|
|
55
|
+
"I",
|
|
56
|
+
"ICN",
|
|
57
|
+
"INP",
|
|
58
|
+
"N",
|
|
59
|
+
"PLE",
|
|
60
|
+
"PLW",
|
|
61
|
+
"Q",
|
|
62
|
+
"T",
|
|
63
|
+
"TID",
|
|
64
|
+
"UP",
|
|
65
|
+
"W",
|
|
66
|
+
"ERA",
|
|
67
|
+
"ASYNC",
|
|
68
|
+
"SIM",
|
|
69
|
+
"TD",
|
|
70
|
+
"ARG", # Unused arguments
|
|
71
|
+
"C", # Complexity
|
|
72
|
+
"PIE", # Flake8-pie
|
|
73
|
+
"RET", # Return
|
|
74
|
+
"RSE", # Raise
|
|
75
|
+
"SLF", # Self
|
|
76
|
+
"T10", # Todo
|
|
77
|
+
"TCH", # Type checking
|
|
78
|
+
"YTT", # Type testing
|
|
79
|
+
"PERF",
|
|
80
|
+
"ANN",
|
|
81
|
+
"COM",
|
|
82
|
+
"S"
|
|
83
|
+
]
|
|
84
|
+
ignore = [
|
|
85
|
+
"N805", "D", "ANN401", "COM812", "S104", "TC", "TD003"
|
|
86
|
+
]
|
|
87
|
+
fixable = ["ALL"]
|
|
88
|
+
|
|
89
|
+
[tool.ruff.lint.per-file-ignores]
|
|
90
|
+
"tests/**" = ["S101", "ANN"]
|
|
91
|
+
|
|
92
|
+
[tool.ruff.lint.pylint]
|
|
93
|
+
max-returns = 5
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rapis
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
Requires-Python: >=3.14
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: granian>=2.7.4
|
|
8
|
+
Requires-Dist: msgspec>=0.21.1
|
|
9
|
+
|
|
10
|
+
# Rapis - Minimalistic web library
|
|
11
|
+
|
|
12
|
+
this library was inspired by FastAPI so syntax may be identical
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from rapis import AppRouter, WebApp
|
|
16
|
+
|
|
17
|
+
app = WebApp()
|
|
18
|
+
router = AppRouter()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@router.get("/")
|
|
22
|
+
async def root() -> dict:
|
|
23
|
+
return {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
app.include_router(router)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
### ! WARNING: Library in early development, it is NOT READY for production
|
|
32
|
+
|
|
33
|
+
### from Pypi
|
|
34
|
+
|
|
35
|
+
#### WIP
|
|
36
|
+
|
|
37
|
+
### from source
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
git clone https://github.com/sheptalo/rapis folder
|
|
41
|
+
pip install ./folder
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## DOCS will be implemented soon
|
|
45
|
+
|
|
46
|
+
## TODO
|
|
47
|
+
|
|
48
|
+
- [ ] Exception handling
|
|
49
|
+
- [ ] Request/Response Work model
|
|
50
|
+
- [ ] Docs
|
|
51
|
+
- [ ] More availabilities to expand logic
|
|
52
|
+
- [ ] better Query params handle
|
|
53
|
+
- [ ] chage routing from linear to something else
|
|
54
|
+
- [ ] rewrite path patterns logic
|
|
55
|
+
- [ ] review Middleware logic (it was taked from fastapi)
|
|
56
|
+
- [ ] websocket support(maybe)
|
|
57
|
+
- [ ] coverage
|
|
58
|
+
- [ ] typing support (for now a few Errors in mypy, maybe start using TY)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
rapis.egg-info/PKG-INFO
|
|
4
|
+
rapis.egg-info/SOURCES.txt
|
|
5
|
+
rapis.egg-info/dependency_links.txt
|
|
6
|
+
rapis.egg-info/requires.txt
|
|
7
|
+
rapis.egg-info/top_level.txt
|
|
8
|
+
src/__init__.py
|
|
9
|
+
src/_application.py
|
|
10
|
+
src/_handler.py
|
|
11
|
+
src/_middleware.py
|
|
12
|
+
src/_params.py
|
|
13
|
+
src/_path_pattern.py
|
|
14
|
+
src/_request.py
|
|
15
|
+
src/_response.py
|
|
16
|
+
src/_route.py
|
|
17
|
+
src/_router.py
|
|
18
|
+
src/_types.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
rapis
|
rapis-0.0.1/setup.cfg
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from functools import reduce
|
|
3
|
+
|
|
4
|
+
from granian._granian import RSGIHTTPProtocol
|
|
5
|
+
from granian.rsgi import Scope
|
|
6
|
+
|
|
7
|
+
from ._middleware import Middleware
|
|
8
|
+
from ._router import AppRouter
|
|
9
|
+
from ._types import RSGIApp
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class WebApp:
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
*,
|
|
16
|
+
root_path: str = "",
|
|
17
|
+
middlewares: Sequence[Middleware] | None = None,
|
|
18
|
+
) -> None:
|
|
19
|
+
if not middlewares:
|
|
20
|
+
middlewares = []
|
|
21
|
+
self.router = AppRouter(prefix=root_path)
|
|
22
|
+
self.root_path = root_path
|
|
23
|
+
self.middleware_stack: RSGIApp = reduce(
|
|
24
|
+
lambda app, mw: mw.cls(app, *mw.args, **mw.kwargs),
|
|
25
|
+
reversed(middlewares),
|
|
26
|
+
self.router,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
async def __call__(self, scope: Scope, proto: RSGIHTTPProtocol) -> None:
|
|
30
|
+
await self.middleware_stack(scope, proto)
|
|
31
|
+
|
|
32
|
+
def include_router(self, router: AppRouter) -> None:
|
|
33
|
+
for route in router.routes:
|
|
34
|
+
route.path = self.router.prefix + route.path
|
|
35
|
+
self.router.routes.append(route)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from collections.abc import Callable
|
|
3
|
+
from contextlib import suppress
|
|
4
|
+
from contextvars import ContextVar, Token
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from http import HTTPStatus
|
|
7
|
+
from typing import Any, Literal, get_type_hints
|
|
8
|
+
from urllib.parse import parse_qsl
|
|
9
|
+
|
|
10
|
+
import msgspec
|
|
11
|
+
from granian._granian import RSGIHTTPProtocol
|
|
12
|
+
from granian.rsgi import Scope
|
|
13
|
+
from msgspec import DecodeError, Struct
|
|
14
|
+
|
|
15
|
+
from ._types import Query
|
|
16
|
+
|
|
17
|
+
_path_params: ContextVar[dict[str, str] | None] = ContextVar(
|
|
18
|
+
"_path_params", default=None
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def path_params_context_token(
|
|
23
|
+
params: dict[str, str],
|
|
24
|
+
) -> Token[dict[str, str] | None]:
|
|
25
|
+
return _path_params.set(params)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def reset_path_params_context(token: Token[dict[str, str] | None]) -> None:
|
|
29
|
+
_path_params.reset(token)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _current_path_params() -> dict[str, str]:
|
|
33
|
+
v = _path_params.get()
|
|
34
|
+
return v if v is not None else {}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class _ParamBinding:
|
|
39
|
+
name: str
|
|
40
|
+
source: Literal["path", "query", "body"]
|
|
41
|
+
type: type
|
|
42
|
+
is_struct: bool
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Handler:
|
|
46
|
+
def __init__(
|
|
47
|
+
self, call: Callable[..., Any], status: HTTPStatus = HTTPStatus.OK
|
|
48
|
+
) -> None:
|
|
49
|
+
self.call = call
|
|
50
|
+
self.status = status
|
|
51
|
+
self.path_fields: frozenset[str] = frozenset()
|
|
52
|
+
self.bindings: tuple[_ParamBinding, ...] = tuple(
|
|
53
|
+
_extract_bindings(call, frozenset())
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def set_path_fields(self, path_fields: frozenset[str]) -> None:
|
|
57
|
+
self.path_fields = path_fields
|
|
58
|
+
self.bindings = tuple(_extract_bindings(self.call, path_fields))
|
|
59
|
+
|
|
60
|
+
async def __call__(self, scope: Scope, proto: RSGIHTTPProtocol) -> None:
|
|
61
|
+
kwargs = await self.prepare(scope, proto)
|
|
62
|
+
result = await self.call(**kwargs)
|
|
63
|
+
await self.write_response(result, proto)
|
|
64
|
+
|
|
65
|
+
async def prepare(
|
|
66
|
+
self, scope: Scope, proto: RSGIHTTPProtocol
|
|
67
|
+
) -> dict[str, Any]:
|
|
68
|
+
kwargs: dict[str, Any] = {}
|
|
69
|
+
decoded_body = {}
|
|
70
|
+
with suppress(DecodeError):
|
|
71
|
+
decoded_body = msgspec.json.decode(await proto())
|
|
72
|
+
query_dict = dict(parse_qsl(scope.query_string))
|
|
73
|
+
path_ctx = _current_path_params()
|
|
74
|
+
|
|
75
|
+
for b in self.bindings:
|
|
76
|
+
if not b.is_struct:
|
|
77
|
+
if b.source == "path":
|
|
78
|
+
kwargs[b.name] = b.type(path_ctx[b.name])
|
|
79
|
+
elif b.source == "query":
|
|
80
|
+
kwargs[b.name] = b.type(query_dict.get(b.name))
|
|
81
|
+
else:
|
|
82
|
+
kwargs[b.name] = b.type(decoded_body.get(b.name))
|
|
83
|
+
elif b.source == "path":
|
|
84
|
+
fields = getattr(b.type, "__struct_fields__", ())
|
|
85
|
+
subset = {k: path_ctx[k] for k in fields if k in path_ctx}
|
|
86
|
+
kwargs[b.name] = msgspec.convert(subset, type=b.type)
|
|
87
|
+
elif b.source == "query":
|
|
88
|
+
kwargs[b.name] = msgspec.convert(query_dict, b.type)
|
|
89
|
+
else:
|
|
90
|
+
kwargs[b.name] = msgspec.convert(decoded_body, type=b.type)
|
|
91
|
+
return kwargs
|
|
92
|
+
|
|
93
|
+
async def write_response(
|
|
94
|
+
self, result: Any, proto: RSGIHTTPProtocol
|
|
95
|
+
) -> None:
|
|
96
|
+
payload = result
|
|
97
|
+
if isinstance(result, Struct | dict):
|
|
98
|
+
payload = msgspec.json.encode(result)
|
|
99
|
+
elif isinstance(result, str):
|
|
100
|
+
payload = result.encode()
|
|
101
|
+
|
|
102
|
+
proto.response_bytes(
|
|
103
|
+
self.status, [("Content-Type", "application/json")], payload
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _extract_bindings(
|
|
108
|
+
call: Callable[..., Any], path_fields: frozenset[str]
|
|
109
|
+
) -> list[_ParamBinding]:
|
|
110
|
+
sig = inspect.signature(call)
|
|
111
|
+
hints = get_type_hints(call, include_extras=True)
|
|
112
|
+
bindings: list[_ParamBinding] = []
|
|
113
|
+
|
|
114
|
+
for name, param in sig.parameters.items():
|
|
115
|
+
ann = hints.get(name, param.annotation)
|
|
116
|
+
if ann is inspect.Parameter.empty:
|
|
117
|
+
continue
|
|
118
|
+
if not isinstance(ann, type):
|
|
119
|
+
continue
|
|
120
|
+
is_struct = issubclass(ann, Struct)
|
|
121
|
+
if name in path_fields:
|
|
122
|
+
binding_source = "path"
|
|
123
|
+
elif isinstance(param.default, Query):
|
|
124
|
+
binding_source = "query"
|
|
125
|
+
else:
|
|
126
|
+
binding_source = "body"
|
|
127
|
+
bindings.append(
|
|
128
|
+
_ParamBinding(
|
|
129
|
+
name=name, source=binding_source, type=ann, is_struct=is_struct
|
|
130
|
+
)
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
return bindings
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from collections.abc import Iterator
|
|
2
|
+
from typing import Any, Protocol
|
|
3
|
+
|
|
4
|
+
from ._types import RSGIApp
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class _MiddlewareFactory[**P](Protocol):
|
|
8
|
+
def __call__(
|
|
9
|
+
self, app: RSGIApp, /, *args: P.args, **kwargs: P.kwargs
|
|
10
|
+
) -> RSGIApp: ... # pragma: no cover
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Middleware[**P]:
|
|
14
|
+
def __init__(
|
|
15
|
+
self, cls: _MiddlewareFactory[P], *args: P.args, **kwargs: P.kwargs
|
|
16
|
+
) -> None:
|
|
17
|
+
self.cls = cls
|
|
18
|
+
self.args = args
|
|
19
|
+
self.kwargs = kwargs
|
|
20
|
+
|
|
21
|
+
def __iter__(self) -> Iterator[Any]:
|
|
22
|
+
as_tuple = (self.cls, self.args, self.kwargs)
|
|
23
|
+
return iter(as_tuple)
|
|
24
|
+
|
|
25
|
+
def __repr__(self) -> str:
|
|
26
|
+
class_name = self.__class__.__name__
|
|
27
|
+
args_strings = [f"{value!r}" for value in self.args]
|
|
28
|
+
option_strings = [
|
|
29
|
+
f"{key}={value!r}" for key, value in self.kwargs.items()
|
|
30
|
+
]
|
|
31
|
+
name = getattr(self.cls, "__name__", "")
|
|
32
|
+
args_repr = ", ".join([name] + args_strings + option_strings)
|
|
33
|
+
return f"{class_name}({args_repr})"
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from typing import Literal
|
|
3
|
+
from urllib.parse import unquote
|
|
4
|
+
|
|
5
|
+
_PARAM_RE = re.compile(r"^\{([a-zA-Z_][a-zA-Z0-9_]*)\}$")
|
|
6
|
+
|
|
7
|
+
type _SegKind = Literal["literal", "param"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _split_request_path(request_path: str) -> list[str]:
|
|
11
|
+
raw = (request_path or "").split("?", 1)[0].strip()
|
|
12
|
+
if not raw or raw == "/":
|
|
13
|
+
return []
|
|
14
|
+
return [unquote(s) for s in raw.strip("/").split("/") if s]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _split_template_path(template: str) -> list[str]:
|
|
18
|
+
raw = (template or "").strip()
|
|
19
|
+
if not raw or raw == "/":
|
|
20
|
+
return []
|
|
21
|
+
return [s for s in raw.strip("/").split("/") if s]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def compile_route_path(
|
|
25
|
+
template: str,
|
|
26
|
+
) -> tuple[list[tuple[_SegKind, str]], frozenset[str]]:
|
|
27
|
+
"""Return compiled segments and the set of path parameter names."""
|
|
28
|
+
out: list[tuple[_SegKind, str]] = []
|
|
29
|
+
names: set[str] = set()
|
|
30
|
+
for seg in _split_template_path(template):
|
|
31
|
+
m = _PARAM_RE.fullmatch(seg)
|
|
32
|
+
if m:
|
|
33
|
+
name = m.group(1)
|
|
34
|
+
out.append(("param", name))
|
|
35
|
+
names.add(name)
|
|
36
|
+
else:
|
|
37
|
+
if "{" in seg or "}" in seg:
|
|
38
|
+
msg = f"Invalid route segment {seg!r} in template {template!r}"
|
|
39
|
+
raise ValueError(msg)
|
|
40
|
+
out.append(("literal", seg))
|
|
41
|
+
return out, frozenset(names)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def match_route_path(
|
|
45
|
+
compiled: list[tuple[_SegKind, str]], request_path: str
|
|
46
|
+
) -> dict[str, str] | None:
|
|
47
|
+
req_segs = _split_request_path(request_path)
|
|
48
|
+
if len(req_segs) != len(compiled):
|
|
49
|
+
return None
|
|
50
|
+
params: dict[str, str] = {}
|
|
51
|
+
for (kind, val), rseg in zip(compiled, req_segs, strict=True):
|
|
52
|
+
if kind == "literal":
|
|
53
|
+
if val != rseg:
|
|
54
|
+
return None
|
|
55
|
+
else:
|
|
56
|
+
params[val] = rseg
|
|
57
|
+
return params
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from collections.abc import Callable, Collection, Sequence
|
|
2
|
+
from http import HTTPMethod, HTTPStatus
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from granian._granian import RSGIHTTPProtocol
|
|
6
|
+
from granian.rsgi import Scope
|
|
7
|
+
|
|
8
|
+
from ._handler import (
|
|
9
|
+
Handler,
|
|
10
|
+
path_params_context_token,
|
|
11
|
+
reset_path_params_context,
|
|
12
|
+
)
|
|
13
|
+
from ._middleware import Middleware
|
|
14
|
+
from ._path_pattern import compile_route_path, match_route_path
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Route:
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
path: str,
|
|
21
|
+
endpoint: Callable[..., Any],
|
|
22
|
+
*,
|
|
23
|
+
methods: Collection[HTTPMethod] | None = None,
|
|
24
|
+
middleware: Sequence[Middleware] | None = None,
|
|
25
|
+
) -> None:
|
|
26
|
+
self._path = path
|
|
27
|
+
self._compiled, self._path_field_names = compile_route_path(path)
|
|
28
|
+
self.endpoint = endpoint
|
|
29
|
+
|
|
30
|
+
if isinstance(endpoint, Handler):
|
|
31
|
+
endpoint.set_path_fields(self._path_field_names)
|
|
32
|
+
|
|
33
|
+
self.app = endpoint
|
|
34
|
+
|
|
35
|
+
if middleware is not None:
|
|
36
|
+
for cls, args, kwargs in reversed(middleware):
|
|
37
|
+
self.app = cls(self.app, *args, **kwargs)
|
|
38
|
+
|
|
39
|
+
if methods is None:
|
|
40
|
+
self.methods = None
|
|
41
|
+
else:
|
|
42
|
+
self.methods = {method.upper() for method in methods}
|
|
43
|
+
if "GET" in self.methods:
|
|
44
|
+
self.methods.add("HEAD")
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def path(self) -> str:
|
|
48
|
+
return self._path
|
|
49
|
+
|
|
50
|
+
@path.setter
|
|
51
|
+
def path(self, value: str) -> None:
|
|
52
|
+
self._path = value
|
|
53
|
+
self._compiled, self._path_field_names = compile_route_path(value)
|
|
54
|
+
if isinstance(self.endpoint, Handler):
|
|
55
|
+
self.endpoint.set_path_fields(self._path_field_names)
|
|
56
|
+
|
|
57
|
+
async def __call__(self, scope: Scope, proto: RSGIHTTPProtocol) -> None:
|
|
58
|
+
matched = match_route_path(self._compiled, scope.path)
|
|
59
|
+
if matched is None:
|
|
60
|
+
proto.response_str(HTTPStatus.NOT_FOUND, [], "Not found")
|
|
61
|
+
return
|
|
62
|
+
await self.handle(scope, proto, matched)
|
|
63
|
+
|
|
64
|
+
def matches(self, scope: Scope) -> bool:
|
|
65
|
+
return match_route_path(self._compiled, scope.path) is not None
|
|
66
|
+
|
|
67
|
+
async def handle(
|
|
68
|
+
self,
|
|
69
|
+
scope: Scope,
|
|
70
|
+
proto: RSGIHTTPProtocol,
|
|
71
|
+
matched: dict[str, str],
|
|
72
|
+
) -> None:
|
|
73
|
+
if self.methods and scope.method not in self.methods:
|
|
74
|
+
headers = [("Allow", ", ".join(sorted(self.methods)))]
|
|
75
|
+
proto.response_str(
|
|
76
|
+
HTTPStatus.METHOD_NOT_ALLOWED, headers, "Method Not Allowed"
|
|
77
|
+
)
|
|
78
|
+
return
|
|
79
|
+
|
|
80
|
+
token = path_params_context_token(matched)
|
|
81
|
+
try:
|
|
82
|
+
await self.app(scope, proto)
|
|
83
|
+
finally:
|
|
84
|
+
reset_path_params_context(token)
|
|
85
|
+
|
|
86
|
+
def __eq__(self, other: Any) -> bool:
|
|
87
|
+
return (
|
|
88
|
+
isinstance(other, Route)
|
|
89
|
+
and self.path == other.path
|
|
90
|
+
and self.endpoint == other.endpoint
|
|
91
|
+
and self.methods == other.methods
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def __hash__(self) -> int:
|
|
95
|
+
return hash(self.path)
|
|
96
|
+
|
|
97
|
+
def __repr__(self) -> str:
|
|
98
|
+
return (
|
|
99
|
+
f"{self.__class__.__name__}(path={self.path!r}, "
|
|
100
|
+
f"methods={sorted(self.methods or [])!r})"
|
|
101
|
+
)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
from collections.abc import Callable, Sequence
|
|
2
|
+
from http import HTTPMethod, HTTPStatus
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from granian._granian import RSGIHTTPProtocol
|
|
6
|
+
from granian.rsgi import Scope
|
|
7
|
+
|
|
8
|
+
from ._handler import Handler
|
|
9
|
+
from ._middleware import Middleware
|
|
10
|
+
from ._route import Route
|
|
11
|
+
from ._types import RSGIApp
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AppRouter:
|
|
15
|
+
def __init__( # TODO(): exception handle
|
|
16
|
+
self,
|
|
17
|
+
prefix: str = "",
|
|
18
|
+
middlewares: Sequence[Middleware] | None = None,
|
|
19
|
+
*,
|
|
20
|
+
default: RSGIApp | None = None,
|
|
21
|
+
route_class: type[Route] = Route,
|
|
22
|
+
) -> None:
|
|
23
|
+
if not middlewares:
|
|
24
|
+
middlewares = []
|
|
25
|
+
self.prefix = prefix
|
|
26
|
+
self.routes: list[Route] = []
|
|
27
|
+
self.middlewares = middlewares
|
|
28
|
+
self.route_class = route_class
|
|
29
|
+
self.default = default or self.not_found
|
|
30
|
+
|
|
31
|
+
def route(
|
|
32
|
+
self,
|
|
33
|
+
url: str,
|
|
34
|
+
methods: list[HTTPMethod],
|
|
35
|
+
*,
|
|
36
|
+
status: HTTPStatus = HTTPStatus.OK,
|
|
37
|
+
) -> Callable:
|
|
38
|
+
def deco(func: Callable) -> Callable:
|
|
39
|
+
self.routes.append(
|
|
40
|
+
self.route_class(
|
|
41
|
+
path=self.prefix + url,
|
|
42
|
+
endpoint=Handler(func, status=status),
|
|
43
|
+
methods=methods,
|
|
44
|
+
middleware=self.middlewares,
|
|
45
|
+
)
|
|
46
|
+
)
|
|
47
|
+
return func
|
|
48
|
+
|
|
49
|
+
return deco
|
|
50
|
+
|
|
51
|
+
def head(
|
|
52
|
+
self, url: str, *, status: HTTPStatus = HTTPStatus.OK
|
|
53
|
+
) -> Callable[[Callable], Callable]:
|
|
54
|
+
return self.route(
|
|
55
|
+
url, methods=[HTTPMethod.GET, HTTPMethod.HEAD], status=status
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
def get(
|
|
59
|
+
self, url: str, *, status: HTTPStatus = HTTPStatus.OK
|
|
60
|
+
) -> Callable[[Callable], Callable]:
|
|
61
|
+
return self.route(
|
|
62
|
+
url, methods=[HTTPMethod.GET, HTTPMethod.OPTIONS], status=status
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def post(
|
|
66
|
+
self, url: str, *, status: HTTPStatus = HTTPStatus.OK
|
|
67
|
+
) -> Callable[[Callable], Callable]:
|
|
68
|
+
return self.route(url, methods=[HTTPMethod.POST], status=status)
|
|
69
|
+
|
|
70
|
+
def patch(
|
|
71
|
+
self, url: str, *, status: HTTPStatus = HTTPStatus.OK
|
|
72
|
+
) -> Callable[[Callable], Callable]:
|
|
73
|
+
return self.route(url, methods=[HTTPMethod.PATCH], status=status)
|
|
74
|
+
|
|
75
|
+
def put(
|
|
76
|
+
self, url: str, *, status: HTTPStatus = HTTPStatus.OK
|
|
77
|
+
) -> Callable[[Callable], Callable]:
|
|
78
|
+
return self.route(url, methods=[HTTPMethod.PUT], status=status)
|
|
79
|
+
|
|
80
|
+
def delete(
|
|
81
|
+
self, url: str, *, status: HTTPStatus = HTTPStatus.OK
|
|
82
|
+
) -> Callable[[Callable], Callable]:
|
|
83
|
+
return self.route(url, methods=[HTTPMethod.DELETE], status=status)
|
|
84
|
+
|
|
85
|
+
def trace(
|
|
86
|
+
self, url: str, *, status: HTTPStatus = HTTPStatus.OK
|
|
87
|
+
) -> Callable[[Callable], Callable]:
|
|
88
|
+
return self.route(url, methods=[HTTPMethod.TRACE], status=status)
|
|
89
|
+
|
|
90
|
+
async def __call__(self, scope: Scope, proto: RSGIHTTPProtocol) -> Any:
|
|
91
|
+
for route in self.routes:
|
|
92
|
+
if route.matches(scope):
|
|
93
|
+
await route(scope, proto)
|
|
94
|
+
break
|
|
95
|
+
else:
|
|
96
|
+
await self.default(scope, proto)
|
|
97
|
+
|
|
98
|
+
async def not_found(self, scope: Scope, proto: RSGIHTTPProtocol) -> Any:
|
|
99
|
+
if scope.scheme == "http":
|
|
100
|
+
proto.response_str(
|
|
101
|
+
HTTPStatus.NOT_FOUND,
|
|
102
|
+
[("Content-type", "application/json")],
|
|
103
|
+
'{"detail":"Not Found"',
|
|
104
|
+
)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from collections.abc import Awaitable, Callable
|
|
2
|
+
|
|
3
|
+
from granian._granian import RSGIHTTPProtocol
|
|
4
|
+
from granian.rsgi import Scope
|
|
5
|
+
|
|
6
|
+
type RSGIApp = Callable[[Scope, RSGIHTTPProtocol], Awaitable[None]]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Query[T]:
|
|
10
|
+
def __init__(self, default: T | None = None) -> None:
|
|
11
|
+
self.default = default
|