Django status notifications with ntfy.sh
There are a gazillion ways to get status notifications for a web application, but here's another one using ntfy.sh
This little helper function would need to be scheduled to run in a task queue like django-q2. It could also be modified slightly into a cron job.
def ntfy_status() -> str:
"""Checks the health check endpoint and sends a notification to ntfy.sh."""
import requests
from django.contrib.sites.models import Site
from django.urls import reverse
if not settings.NTFY_TOPIC:
raise ValueError("NTFY_TOPIC environment variable is not configured.")
# Create the full url to a health check
protocol = "https" if settings.SECURE_SSL_REDIRECT else "http"
domain = Site.objects.get_current().domain
path = reverse("health_check")
url = f"{protocol}://{domain}{path}"
health_response = requests.get(url)
if health_response.status_code == 200:
emoji = "green_circle"
suffix = "is up!"
else:
emoji = "red_circle,skull"
suffix = "is down!"
# Send ntfy message
ntfy_response = requests.post(
f"https://ntfy.sh/{settings.NTFY_TOPIC}",
data=f"{domain} {suffix}",
headers={
"Tags": f"{emoji},{health_response.status_code}",
"Actions": "view, Open URL, {url}, clear=true",
},
)
ntfy_response.raise_for_status()
return "Sent notification to ntfy.sh with status code: " + str(ntfy_response.status_code)
