Flask Prometheus Metrics

raw JSON →
1.0.0 verified Fri May 01 auth: no python

A Flask extension that provides Prometheus metrics for Flask web applications with minimal configuration. Version 1.0.0 supports Python >=3.6 and offers a straightforward API to expose metrics like request count, request duration, and custom metrics via a /metrics endpoint.

pip install flask-prometheus-metrics
error ImportError: cannot import name 'PrometheusMetrics' from 'flask_prometheus_metrics'
cause Outdated installation or wrong package name; flask_prometheus_metrics is not installed.
fix
Run: pip install flask-prometheus-metrics (note hyphens in package name, underscores in import).
error AttributeError: 'PrometheusMetrics' object has no attribute 'register_default'
cause Method renamed in newer versions; register_default is deprecated.
fix
Use metrics.register_default() - if available, or check documentation for current API. For 1.0.0, this method is still present.
error KeyError: 'flask_exporter_info' in metrics endpoint
cause Missing required metric or exporter info; likely due to incomplete configuration.
fix
Ensure you call register_metrics(app) with the app argument, or initialize PrometheusMetrics(app).
gotcha The default /metrics endpoint is not protected; anyone can access it. In production, ensure it's secured or exported via a separate sidecar.
fix Use a reverse proxy or add authentication via Flask decorators before the /metrics route.
gotcha If you use register_metrics() separately, it expects a Flask app or blueprint; otherwise metrics won't update. Common mistake: calling after app creation without passing the app.
fix Pass the Flask app instance to register_metrics(), e.g., register_metrics(app).
deprecated The old import path flask_prometheus_metrics.metrics is deprecated. All metrics are accessible from the top-level package now.
fix Use from flask_prometheus_metrics import PrometheusMetrics instead.

Initialize PrometheusMetrics with the Flask app. By default, metrics are exposed at /metrics.

from flask import Flask
from flask_prometheus_metrics import PrometheusMetrics

app = Flask(__name__)
metrics = PrometheusMetrics(app)

@app.route('/')
def hello():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()