Skip to content

Commit

Permalink
AioHTTP improvements:
Browse files Browse the repository at this point in the history
- if middleware order matters you can use get_middleware instead of add_middleware
- fix `is_handled` parameter calculation for path_template
  • Loading branch information
alexreznikoff committed Feb 26, 2025
1 parent 1f53b61 commit 77fb5bc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "huntflow-base-metrics"
version = "0.2.0"
version = "0.2.1"
description = "Prometheus metrics for Huntflow services"
authors = [
{name = "Developers huntflow", email = "[email protected]"},
Expand Down
25 changes: 23 additions & 2 deletions src/huntflow_base_metrics/web_frameworks/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from huntflow_base_metrics.export import export_to_http_response
from huntflow_base_metrics.web_frameworks._middleware import PathTemplate, PrometheusMiddleware

__all__ = ["add_middleware", "get_http_response_metrics"]
__all__ = ["add_middleware", "get_http_response_metrics", "get_middleware"]


class _PrometheusMiddleware(PrometheusMiddleware[Request]):
Expand Down Expand Up @@ -42,9 +42,11 @@ def get_method(request: Request) -> str:
def get_path_template(request: Request) -> PathTemplate:
match_info = request.match_info
value = request.rel_url.path
is_handled = False
if match_info and match_info.route.resource:
value = match_info.route.resource.canonical
return PathTemplate(value=value, is_handled=match_info is not None)
is_handled = True
return PathTemplate(value=value, is_handled=is_handled)


def add_middleware(
Expand All @@ -67,6 +69,25 @@ def add_middleware(
app.middlewares.append(_PrometheusMiddleware.dispatch)


def get_middleware(
include_routes: Optional[Iterable[str]] = None,
exclude_routes: Optional[Iterable[str]] = None,
) -> Callable:
"""
Returns observing middleware to the given AioHTTP application.
Use if middleware order matters.
:param include_routes: optional set of path templates to observe.
If it's not empty, then only the specified routes will be observed
(also exclude_routes will be ignored).
:param exclude_routes: optional set of path templates to not observe.
If it's not empty (and include_routes is not specified), then the
specified routes will not be observed.
"""
_PrometheusMiddleware.configure(include_routes, exclude_routes)
return _PrometheusMiddleware.dispatch


def get_http_response_metrics() -> Response:
"""Method returns HTTP Response with current metrics in prometheus format."""
content, content_type = export_to_http_response()
Expand Down

0 comments on commit 77fb5bc

Please sign in to comment.