Use Django messages framework when a webhook is called

144 Views Asked by At

I have set up an URL in Django that is being used as webhook from another service. It has implemented like:

@csrf_exempt
@require_POST
def hoof_alert(request):
   json_rx = json.loads(request.body.decode("utf-8"))
   if json_rx["alerts"][0]["status"] == "firing":
      messages.error("Alarm fired")
   else:
      messages.success("No more alarm")
   returns HttpResponse(status=200)

Now, the main issue is that, even if the function is called, as I see it happens on the console and my service get back the code 200 status, I can't see the message popping up on the front end.

My guess is that, the message is attached to the request done on the webhook, which is not the request an user will do when access the website.

So, my question is, how do I make the message being visible on the front end when the hook is called?

More Info: The webhook is called by a Grafana client when an alarm is fired so, there's no human request behind it. I need the message to appear on the front end as soon as someone request another page of my Django application

The idea is:

  1. Grafana calls the webhook
  2. The Webhook is fired and the message is created
  3. If someone access the Django application frontend the message must be shown
1

There are 1 best solutions below

4
Rayees AC On

Return JSON Response Modify your webhook view to return a JSON response with the message content. Then, in your front-end code, you can handle this JSON response and display the message as needed.

from django.http import JsonResponse

@csrf_exempt
@require_POST
def hoof_alert(request):
    json_rx = json.loads(request.body.decode("utf-8"))
    if json_rx["alerts"][0]["status"] == "firing":
        message = "Alarm fired"
    else:
        message = "No more alarm"
    return JsonResponse({"message": message})