Skip to content

Commit 77fb5bc

Browse files
committed
AioHTTP improvements:
- if middleware order matters you can use get_middleware instead of add_middleware - fix `is_handled` parameter calculation for path_template
1 parent 1f53b61 commit 77fb5bc

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

pyproject.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "huntflow-base-metrics"
3-
version = "0.2.0"
3+
version = "0.2.1"
44
description = "Prometheus metrics for Huntflow services"
55
authors = [
66
{name = "Developers huntflow", email = "[email protected]"},

src/huntflow_base_metrics/web_frameworks/aiohttp.py

+23-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from huntflow_base_metrics.export import export_to_http_response
88
from huntflow_base_metrics.web_frameworks._middleware import PathTemplate, PrometheusMiddleware
99

10-
__all__ = ["add_middleware", "get_http_response_metrics"]
10+
__all__ = ["add_middleware", "get_http_response_metrics", "get_middleware"]
1111

1212

1313
class _PrometheusMiddleware(PrometheusMiddleware[Request]):
@@ -42,9 +42,11 @@ def get_method(request: Request) -> str:
4242
def get_path_template(request: Request) -> PathTemplate:
4343
match_info = request.match_info
4444
value = request.rel_url.path
45+
is_handled = False
4546
if match_info and match_info.route.resource:
4647
value = match_info.route.resource.canonical
47-
return PathTemplate(value=value, is_handled=match_info is not None)
48+
is_handled = True
49+
return PathTemplate(value=value, is_handled=is_handled)
4850

4951

5052
def add_middleware(
@@ -67,6 +69,25 @@ def add_middleware(
6769
app.middlewares.append(_PrometheusMiddleware.dispatch)
6870

6971

72+
def get_middleware(
73+
include_routes: Optional[Iterable[str]] = None,
74+
exclude_routes: Optional[Iterable[str]] = None,
75+
) -> Callable:
76+
"""
77+
Returns observing middleware to the given AioHTTP application.
78+
Use if middleware order matters.
79+
80+
:param include_routes: optional set of path templates to observe.
81+
If it's not empty, then only the specified routes will be observed
82+
(also exclude_routes will be ignored).
83+
:param exclude_routes: optional set of path templates to not observe.
84+
If it's not empty (and include_routes is not specified), then the
85+
specified routes will not be observed.
86+
"""
87+
_PrometheusMiddleware.configure(include_routes, exclude_routes)
88+
return _PrometheusMiddleware.dispatch
89+
90+
7091
def get_http_response_metrics() -> Response:
7192
"""Method returns HTTP Response with current metrics in prometheus format."""
7293
content, content_type = export_to_http_response()

0 commit comments

Comments
 (0)