rapis 0.0.1__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.
rapis/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from ._application import WebApp
2
+ from ._middleware import Middleware
3
+ from ._params import query
4
+ from ._router import AppRouter
5
+
6
+ __all__ = ["WebApp", "query", "Middleware", "AppRouter"]
rapis/_application.py 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)
rapis/_handler.py ADDED
@@ -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
rapis/_middleware.py ADDED
@@ -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})"
rapis/_params.py ADDED
@@ -0,0 +1,7 @@
1
+ from typing import Any
2
+
3
+ from ._types import Query as TQuery
4
+
5
+
6
+ def query(default: Any | None = None) -> Any:
7
+ return TQuery(default)
rapis/_path_pattern.py ADDED
@@ -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
rapis/_request.py ADDED
File without changes
rapis/_response.py ADDED
File without changes
rapis/_route.py ADDED
@@ -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
+ )
rapis/_router.py ADDED
@@ -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
+ )
rapis/_types.py ADDED
@@ -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
@@ -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,15 @@
1
+ rapis/__init__.py,sha256=lhFd1LeUGLb5s-Lx5yI1rWTYpROyS6gzXoKtHmyCAL4,185
2
+ rapis/_application.py,sha256=iF6lpRzqZumM5OkZb_FvY_lCg4KSENL1gwTQu5RdAIU,1049
3
+ rapis/_handler.py,sha256=P_gTTKfQYbF_E26QrjVD7CUiqbrD2_METCRjlDvx1Xc,4272
4
+ rapis/_middleware.py,sha256=cjzxGczkk42ckHklwyqflWsinznBxcI15NqpFUGkrAo,1011
5
+ rapis/_params.py,sha256=JVRN4H1ZuaoTZUY7VhQ9TZAKvsA8W0HFhrUBbSVdwR0,135
6
+ rapis/_path_pattern.py,sha256=6lhTbUktg5fkl085AniPUs2wfp58yofil-6iPnxfnko,1748
7
+ rapis/_request.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ rapis/_response.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ rapis/_route.py,sha256=JYhq7pdatBSlPbI6HLES5ffDCQnGK-8t9fdcxJlAP3I,3107
10
+ rapis/_router.py,sha256=-p0voyMANgGJCoEJhmiZ7XJ8FyXw_E9nKL6pQoCpYAQ,3351
11
+ rapis/_types.py,sha256=Hnxhznpc8qkA7_ub_u1w6dLVAyGGIRrmsNrY2iUSD_I,302
12
+ rapis-0.0.1.dist-info/METADATA,sha256=eVa8OgkNwzdcIXv3H9Kh5t64taHYl1dszJUgUK45LEs,1158
13
+ rapis-0.0.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
14
+ rapis-0.0.1.dist-info/top_level.txt,sha256=19-jMfwRGYrBV2-1EWh3y9nsCJeePznVdFr6BlO-iLo,6
15
+ rapis-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ rapis