A Prometheus Python client library for asyncio-based applications

Overview
https://github.com/claws/aioprometheus/workflows/Python%20Package%20Workflow/badge.svg?branch=master https://readthedocs.org/projects/aioprometheus/badge/?version=latest

aioprometheus

aioprometheus is a Prometheus Python client library for asyncio-based applications. It provides metrics collection and serving capabilities, supports multiple data formats and pushing metrics to a gateway.

The project documentation can be found on ReadTheDocs.

Install

$ pip install aioprometheus

A Prometheus Push Gateway client and ASGI service are also included, but their dependencies are not installed by default. You can install them alongside aioprometheus by running:

$ pip install aioprometheus[aiohttp]

Prometheus 2.0 removed support for the binary protocol, so in version 20.0.0 the dependency on prometheus-metrics-proto, which provides binary support, is now optional. If you want binary response support, for use with an older Prometheus, you will need to specify the 'binary' optional extra:

$ pip install aioprometheus[binary]

Multiple optional dependencies can be listed at once, such as:

$ pip install aioprometheus[aiohttp,binary]

Example

The example below shows a single Counter metric collector being created and exposed via the optional aiohttp service endpoint.

#!/usr/bin/env python
"""
This example demonstrates how a single Counter metric collector can be created
and exposed via a HTTP endpoint.
"""
import asyncio
import socket
from aioprometheus import Counter, Service


if __name__ == "__main__":

    async def main(svr: Service) -> None:

        events_counter = Counter(
            "events", "Number of events.", const_labels={"host": socket.gethostname()}
        )
        svr.register(events_counter)
        await svr.start(addr="127.0.0.1", port=5000)
        print(f"Serving prometheus metrics on: {svr.metrics_url}")

        # Now start another coroutine to periodically update a metric to
        # simulate the application making some progress.
        async def updater(c: Counter):
            while True:
                c.inc({"kind": "timer_expiry"})
                await asyncio.sleep(1.0)

        await updater(events_counter)

    loop = asyncio.get_event_loop()
    svr = Service()
    try:
        loop.run_until_complete(main(svr))
    except KeyboardInterrupt:
        pass
    finally:
        loop.run_until_complete(svr.stop())
    loop.close()

In this simple example the counter metric is tracking the number of while loop iterations executed by the updater coroutine. In a realistic application a metric might track the number of requests, etc.

Following typical asyncio usage, an event loop is instantiated first then a metrics service is instantiated. The metrics service is responsible for managing metric collectors and responding to metrics requests.

The service accepts various arguments such as the interface and port to bind to. A collector registry is used within the service to hold metrics collectors that will be exposed by the service. The service will create a new collector registry if one is not passed in.

A counter metric is created and registered with the service. The service is started and then a coroutine is started to periodically update the metric to simulate progress.

This example and demonstration requires some optional extra to be installed.

$ pip install aioprometheus[aiohttp,binary]

The example script can then be run using:

(venv) $ cd examples
(venv) $ python simple-example.py
Serving prometheus metrics on: http://127.0.0.1:5000/metrics

In another terminal fetch the metrics using the curl command line tool to verify they can be retrieved by Prometheus server.

By default metrics will be returned in plan text format.

$ curl http://127.0.0.1:5000/metrics
# HELP events Number of events.
# TYPE events counter
events{host="alpha",kind="timer_expiry"} 33

Similarly, you can request metrics in binary format, though the output will be hard to read on the command line.

$ curl http://127.0.0.1:5000/metrics -H "ACCEPT: application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited"

The metrics service also responds to requests sent to its / route. The response is simple HTML. This route can be useful as a Kubernetes /healthz style health indicator as it does not incur any overhead within the service to serialize a full metrics response.

$ curl http://127.0.0.1:5000/
<html><body><a href='/metrics'>metrics</a></body></html>

The aioprometheus package provides a number of convenience decorator functions that can assist with updating metrics.

The examples directory contains many examples showing how to use the aioprometheus package. The app-example.py file will likely be of interest as it provides a more representative application example than the simple example shown above.

Examples in the examples/frameworks directory show how aioprometheus can be used within various web application frameworks without needing to create a separate aioprometheus.Service endpoint to handle metrics. The FastAPI example is shown below.

#!/usr/bin/env python
"""
Sometimes you may not want to expose Prometheus metrics from a dedicated
Prometheus metrics server but instead want to use an existing web framework.

This example uses the registry from the aioprometheus package to add
Prometheus instrumentation to a FastAPI application. In this example a registry
and a counter metric is instantiated and gets updated whenever the "/" route
is accessed. A '/metrics' route is added to the application using the standard
web framework method. The metrics route renders Prometheus metrics into the
appropriate format.

Run:

  $ pip install fastapi uvicorn
  $ uvicorn fastapi_example:app

"""

from aioprometheus import render, Counter, Registry
from fastapi import FastAPI, Header, Response
from typing import List


app = FastAPI()
app.registry = Registry()
app.events_counter = Counter("events", "Number of events.")
app.registry.register(app.events_counter)


@app.get("/")
async def hello():
    app.events_counter.inc({"path": "/"})
    return "hello"


@app.get("/metrics")
async def handle_metrics(response: Response, accept: List[str] = Header(None)):
    content, http_headers = render(app.registry, accept)
    return Response(content=content, media_type=http_headers["Content-Type"])

License

aioprometheus is released under the MIT license.

aioprometheus originates from the (now deprecated) prometheus python package which was released under the MIT license. aioprometheus continues to use the MIT license and contains a copy of the original MIT license from the prometheus-python project as instructed by the original license.

Web Inventory tool, takes screenshots of webpages using Pyppeteer (headless Chrome/Chromium) and provides some extra bells & whistles to make life easier.

WitnessMe WitnessMe is primarily a Web Inventory tool inspired by Eyewitness, its also written to be extensible allowing you to create custom function

byt3bl33d3r 648 Jan 05, 2023
📦 Autowiring dependency injection container for python 3

Lagom - Dependency injection container What Lagom is a dependency injection container designed to give you "just enough" help with building your depen

Steve B 146 Dec 29, 2022
signal-cli-rest-api is a wrapper around signal-cli and allows you to interact with it through http requests

signal-cli-rest-api signal-cli-rest-api is a wrapper around signal-cli and allows you to interact with it through http requests. Features register/ver

Sebastian Noel Lübke 31 Dec 09, 2022
Generate FastAPI projects for high performance applications

Generate FastAPI projects for high performance applications. Based on MVC architectural pattern, WSGI + ASGI. Includes tests, pipeline, base utilities, Helm chart, and script for bootstrapping local

Radosław Szamszur 274 Jan 08, 2023
Money Transaction is a system based on the recent famous FastAPI.

moneyTransfer Overview Money Transaction is a system based on the recent famous FastAPI. techniques selection System's technique selection is as follo

2 Apr 28, 2021
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 565 Jan 02, 2023
Example of using FastAPI and MongoDB database.

FastAPI Todo Application Example of using FastAPI and MangoDB database. 💡 Prerequisites Python ⚙️ Build & Run The first thing to do is to clone the r

Bobynets Ivan 1 Oct 29, 2021
A Jupyter server based on FastAPI (Experimental)

jupyverse is experimental and should not be used in place of jupyter-server, which is the official Jupyter server.

Jupyter Server 122 Dec 27, 2022
FastAPI + Django experiment

django-fastapi-example This is an experiment to demonstrate one potential way of running FastAPI with Django. It won't be actively maintained. If you'

Jordan Eremieff 78 Jan 03, 2023
A minimalistic example of preparing a model for (synchronous) inference in production.

A minimalistic example of preparing a model for (synchronous) inference in production.

Anton Lozhkov 6 Nov 29, 2021
Analytics service that is part of iter8. Robust analytics and control to unleash cloud-native continuous experimentation.

iter8-analytics iter8 enables statistically robust continuous experimentation of microservices in your CI/CD pipelines. For in-depth information about

16 Oct 14, 2021
FastAPI Skeleton App to serve machine learning models production-ready.

FastAPI Model Server Skeleton Serving machine learning models production-ready, fast, easy and secure powered by the great FastAPI by Sebastián Ramíre

268 Jan 01, 2023
row level security for FastAPI framework

Row Level Permissions for FastAPI While trying out the excellent FastApi framework there was one peace missing for me: an easy, declarative way to def

Holger Frey 315 Dec 25, 2022
An image validator using FastAPI.

fast_api_image_validator An image validator using FastAPI.

Kevin Zehnder 7 Jan 06, 2022
Admin Panel for GinoORM - ready to up & run (just add your models)

Gino-Admin Docs (state: in process): Gino-Admin docs Play with Demo (current master 0.2.3) Gino-Admin demo (login: admin, pass: 1234) Admin

Iuliia Volkova 46 Nov 02, 2022
MLServer

MLServer An open source inference server to serve your machine learning models. ⚠️ This is a Work in Progress. Overview MLServer aims to provide an ea

Seldon 341 Jan 03, 2023
A Prometheus Python client library for asyncio-based applications

aioprometheus aioprometheus is a Prometheus Python client library for asyncio-based applications. It provides metrics collection and serving capabilit

132 Dec 28, 2022
Mnist API server w/ FastAPI

Mnist API server w/ FastAPI

Jinwoo Park (Curt) 8 Feb 08, 2022
基于Pytorch的脚手架项目,Celery+FastAPI+Gunicorn+Nginx+Supervisor实现服务部署,支持Docker发布

cookiecutter-pytorch-fastapi 基于Pytorch的 脚手架项目 按规范添加推理函数即可实现Celery+FastAPI+Gunicorn+Nginx+Supervisor+Docker的快速部署 Requirements Python = 3.6 with pip in

17 Dec 23, 2022
Auth for use with FastAPI

FastAPI Auth Pluggable auth for use with FastAPI Supports OAuth2 Password Flow Uses JWT access and refresh tokens 100% mypy and test coverage Supports

David Montague 95 Jan 02, 2023