Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Quart example #513

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,32 @@ from prometheus_client import start_wsgi_server
start_wsgi_server(8000)
```

#### ASGI

To use Prometheus with [ASGI](http://asgi.readthedocs.org/en/latest/), there is
`make_asgi_app` which creates an ASGI application.

Save the snippet below in a `myapp.py` file

```python
from prometheus_client import make_asgi_app

app = make_asgi_app()
```
Such an application can be useful when integrating Prometheus metrics with ASGI
apps.

The app can be used to serve the metrics through an ASGI implementation, such
as [daphne](https://github.com/django/daphne) or
[uvicorn](https://www.uvicorn.org/).
```bash
# Install daphne if you do not have it
pip install daphne
daphne myapp:app
```

Visit http://localhost:8000/ to see the metrics

#### Flask

To use Prometheus with [Flask](http://flask.pocoo.org/) we need to serve metrics through a Prometheus WSGI application. This can be achieved using [Flask's application dispatching](http://flask.pocoo.org/docs/latest/patterns/appdispatch/). Below is a working example.
Expand Down Expand Up @@ -336,6 +362,40 @@ uwsgi --http 127.0.0.1:8000 --wsgi-file myapp.py --callable app_dispatch

Visit http://localhost:8000/metrics to see the metrics

#### Quart

To use Prometheus with [Quart](https://pgjones.gitlab.io/quart/) we need to
serve metrics through a Prometheus ASGI application. This can be achieved using
[Hypercorn's application dispatching](https://pgjones.gitlab.io/hypercorn/dispatch_apps.html).
Below is a working example.

Save the snippet below in a `myapp.py` file

```python
from quart import Quart
from hypercorn.middleware import DispatcherMiddleware
from prometheus_client import make_asgi_app

# Create my app
app = Quart(__name__)

# Add Prometheus ASGI app to route /metrics
app_dispatch = DispatcherMiddleware({
"/metrics": make_asgi_app(),
"/": app
})
```

Run the example web application like this

```bash
# Install daphne if you do not have it
pip install daphne
daphne myapp:app_dispatch
```

Visit http://localhost:8000/ to see the metrics

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the distinguishing change for this PR.

### Node exporter textfile collector

The [textfile collector](https://github.com/prometheus/node_exporter#textfile-collector)
Expand Down
5 changes: 5 additions & 0 deletions prometheus_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
generate_latest = exposition.generate_latest
MetricsHandler = exposition.MetricsHandler
make_wsgi_app = exposition.make_wsgi_app
try:
# Python >3.5 only
make_asgi_app = exposition.make_asgi_app
except:
pass
start_http_server = exposition.start_http_server
start_wsgi_server = exposition.start_wsgi_server
write_to_textfile = exposition.write_to_textfile
Expand Down
34 changes: 34 additions & 0 deletions prometheus_client/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from urllib.parse import parse_qs

from .exposition import choose_encoder
from .registry import REGISTRY


def make_asgi_app(registry=REGISTRY):
"""Create a ASGI app which serves the metrics from a registry."""

async def prometheus_app(scope, receive, send):
assert scope.get("type") == "http"
params = parse_qs(scope.get('query_string', b''))
r = registry
accept_header = "Accept: " + ",".join([
value.decode("utf8") for (name, value) in scope.get('headers')
if name.decode("utf8") == 'accept'
])
encoder, content_type = choose_encoder(accept_header)
if 'name[]' in params:
r = r.restricted_registry(params['name[]'])
output = encoder(r)

payload = await receive()
if payload.get("type") == "http.request":
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [[b"Content-Type", content_type.encode('utf8')]],
}
)
await send({"type": "http.response.body", "body": output})

return prometheus_app
8 changes: 8 additions & 0 deletions prometheus_client/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
PYTHON26_OR_OLDER = sys.version_info < (2, 7)
PYTHON376_OR_NEWER = sys.version_info > (3, 7, 5)


def make_wsgi_app(registry=REGISTRY):
"""Create a WSGI app which serves the metrics from a registry."""

Expand Down Expand Up @@ -378,3 +379,10 @@ def instance_ip_grouping_key():
with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s:
s.connect(('localhost', 0))
return {'instance': s.getsockname()[0]}


try:
# Python >3.5 only
from .asgi import make_asgi_app
except:
pass