Tiny HTTP router.
from tiny_router.simple import SimpleRouter
router = SimpleRouter()
@router.get("/users/{user_id}")
def get_user(params):
if params.get("user_id") == 1:
return {"id": 1, "name": "Alice"}
route = router.resolve("GET", "/users/{user_id}")
user = route({"user_id": 1})
assert user == {"id": 1, "name": "Alice"}
More examples are in examples/
directory of
repository.
SimpleRouter
: exact-match routerSimpleRegexRouter
: simple regex-based router- Abstract
Router
: user can implement their own routers - Support for type hints
Router class, which can add and resolve routes.
Classes implementing this class must implement abstract method add
and resolve
.
Type of routes passed to add
method.
Type of routes returned from resolve
method.
Shall add a route to the router.
Shall resolve a route, i.e. retrieve an added route from the router.
Should raise RouteNotFound
exception or its subclass if no routes are found.
Return a decorator that adds the decorated object to the router.
For example,
@router.route("GET", "/users")
def route_func(params):
...
is the same as
def route_func(params):
...
router.add("GET", "/users", route_func)
where router
is a router.
Same as route("GET", resource)
.
Same as route("POST", resource)
.
Same as route("PUT", resource)
.
Same as route("PATCH", resource)
.
Same as route("DELETE", resource)
.
Same as route("HEAD", resource)
.
Subclass of Exception
, representing that the route is not found.
Subclass of RouteNotFound
, representing that the method is not allowed.
TODO: 引数なしで raise したらどうなるのか検証 TODO: メンバ変数について追記
Subclass of RouteNotFound
, representing that the resource is not found.
TODO: 引数なしで raise したらどうなるのか検証 TODO: メンバ変数について追記
An implementation of Router[Route, Route]
.
Type of routes passed to add
method or returned from resolve
method.
Add a route to the router.
add
メソッドや route
メソッドで追加されたルートから、
method
と resource
のそれぞれが一致するルートを探して返します。
そのようなルートが存在せず、resource
のみが一致するルートが存在する場合は、
MethodNotAllowed(method)
exception を投げます。
Otherwise, raise ResourceNotFound(resource)
exception.
An implementation of Router[Callable[[Match[str]], ResolvedRoute], ResolvedRoute]
.
matching_precedence
引数は、resolve
メソッドの挙動に影響を与えます。
resolve
メソッドの説明を参照してください。
Type of routes returned from resolve
method.
Add a route to the router.
resource
には正規表現文字列を渡すことができます。
resolve
メソッドの説明を参照してください。
add
メソッドや route
メソッドで追加されたルートから、
method
が一致し、かつこのメソッドの引数の resource
が
そのルートの resource
正規表現文字列にマッチするようなルートを探して返します。
そのようなルートが存在せず、resource
のみがマッチするようなルートが存在する場合は、
MethodNotAllowed(method)
exception を投げます。
Otherwise, raise ResourceNotFound(resource)
exception.
matching_precedence
が first-in
に指定されていた場合、
より最初に追加されたメソッドが優先してマッチします。
last-in
の場合、より最後に追加されたメソッドが優先してマッチします。
返却されるルート (ResolvedRoute
) は、
add
メソッドなどで追加したルート (Callable[[Match[str]], ResolvedRoute]
) に
引数としてマッチしたマッチオブジェクト (Match[str]
) を渡してコールしたときの返り値です。
TODO: translate to english.