|
| 1 | +import os |
| 2 | + |
| 3 | +from django.http import HttpResponse |
| 4 | +from django.views import View |
| 5 | + |
| 6 | +import prometheus_client |
| 7 | +from prometheus_client import multiprocess |
| 8 | +from prometheus_client.exposition import _bake_output |
| 9 | +from prometheus_client.registry import registry |
| 10 | + |
| 11 | + |
| 12 | +class PrometheusDjangoView(View): |
| 13 | + multiprocess_mode: bool = "PROMETHEUS_MULTIPROC_DIR" in os.environ or "prometheus_multiproc_dir" in os.environ |
| 14 | + registry: prometheus_client.CollectorRegistry = None |
| 15 | + |
| 16 | + def get(self, request, *args, **kwargs): |
| 17 | + if self.registry is None: |
| 18 | + if self.multiprocess_mode: |
| 19 | + self.registry = prometheus_client.CollectorRegistry() |
| 20 | + multiprocess.MultiProcessCollector(registry) |
| 21 | + else: |
| 22 | + self.registry = prometheus_client.REGISTRY |
| 23 | + accept_header = request.headers.get("Accept") |
| 24 | + accept_encoding_header = request.headers.get("Accept-Encoding") |
| 25 | + # Bake output |
| 26 | + status, headers, output = _bake_output( |
| 27 | + registry=self.registry, |
| 28 | + accept_header=accept_header, |
| 29 | + accept_encoding_header=accept_encoding_header, |
| 30 | + params=request.GET, |
| 31 | + disable_compression=False, |
| 32 | + ) |
| 33 | + status = int(status.split(" ")[0]) |
| 34 | + return HttpResponse( |
| 35 | + output, |
| 36 | + status=status, |
| 37 | + headers=headers, |
| 38 | + ) |
| 39 | + |
| 40 | + def options(self, request, *args, **kwargs): |
| 41 | + return HttpResponse( |
| 42 | + status=200, |
| 43 | + headers={"Allow": "OPTIONS,GET"}, |
| 44 | + ) |
0 commit comments