|
| 1 | +from django.contrib import admin |
| 2 | +from django.contrib.admin.views.decorators import staff_member_required |
| 3 | +from django.http import Http404, HttpResponse, JsonResponse |
| 4 | +from django.shortcuts import render |
| 5 | +from django.views.decorators.cache import never_cache |
| 6 | + |
| 7 | +from .settings import API_TOKEN |
| 8 | +from .utils import get_scheduler_statistics, get_statistics |
| 9 | + |
| 10 | +try: |
| 11 | + import prometheus_client |
| 12 | + |
| 13 | + from .metrics_collector import RQCollector |
| 14 | +except ImportError: |
| 15 | + prometheus_client = RQCollector = None # type: ignore[assignment, misc] |
| 16 | + |
| 17 | +registry = None |
| 18 | + |
| 19 | + |
| 20 | +@never_cache |
| 21 | +@staff_member_required |
| 22 | +def prometheus_metrics(request): |
| 23 | + global registry |
| 24 | + |
| 25 | + if not RQCollector: # type: ignore[truthy-function] |
| 26 | + raise Http404 |
| 27 | + |
| 28 | + if not registry: |
| 29 | + registry = prometheus_client.CollectorRegistry(auto_describe=True) |
| 30 | + registry.register(RQCollector()) |
| 31 | + |
| 32 | + encoder, content_type = prometheus_client.exposition.choose_encoder(request.META.get('HTTP_ACCEPT', '')) |
| 33 | + if 'name[]' in request.GET: |
| 34 | + registry = registry.restricted_registry(request.GET.getlist('name[]')) |
| 35 | + |
| 36 | + return HttpResponse(encoder(registry), headers={'Content-Type': content_type}) |
| 37 | + |
| 38 | + |
| 39 | +@never_cache |
| 40 | +@staff_member_required |
| 41 | +def stats(request): |
| 42 | + context_data = { |
| 43 | + **admin.site.each_context(request), |
| 44 | + **get_statistics(run_maintenance_tasks=True), |
| 45 | + **get_scheduler_statistics(), |
| 46 | + } |
| 47 | + return render(request, 'django_rq/stats.html', context_data) |
| 48 | + |
| 49 | + |
| 50 | +def stats_json(request, token=None): |
| 51 | + if request.user.is_staff or (token and token == API_TOKEN): |
| 52 | + return JsonResponse(get_statistics()) |
| 53 | + |
| 54 | + return JsonResponse( |
| 55 | + {"error": True, "description": "Please configure API_TOKEN in settings.py before accessing this view."} |
| 56 | + ) |
0 commit comments