Internal Learning
Django signals.py
Lets try to understand how the signals.py works on Django.
⚡ Deep Dive: How signals.py Works and How to Implement It In Django, Signals work like an internal event bus or a publish-subscribe system. They allow certain senders to notify a set of receivers when specific actions take place.
For your system, we use a built-in model signal called post_save. The moment you save or modify an ad campaign on your backend dashboard, Django automatically triggers a background execution to notify your cache clearer.
- Create the signals.py File
Create a new file named signals.py directly inside your ads/ application folder (ads/signals.py):
# ads/signals.py
import requests
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import CentralAdShowcase
@receiver(post_save, sender=CentralAdShowcase)
def purge_jsdelivr_cache(sender, instance, **kwargs):
"""
Listens for any database saves/modifications on CentralAdShowcase.
When a save happens, it fires background HTTP requests to clear the jsDelivr edge cache instantly.
"""
# 1. Check if the ad is active before firing network requests
if instance.is_active:
try:
# We use a short timeout so your admin panel doesn't hang if jsDelivr is slow
requests.get("https://purge.jsdelivr.net/gh/Amitmund/amitmund_ad_widget/config.json", timeout=2)
requests.get("https://purge.jsdelivr.net/gh/Amitmund/amitmund_ad_widget/widget.js", timeout=2)
except requests.RequestException:
# SRE Practice: Fail silently so that network or API blips don't break database saves
pass
- Connect the Signal inside your App Config
Django won't pick up your signals file automatically; you need to import it inside the initialization lifecycle of your application. Open your existing ads/apps.py file and update the ready() method:
# ads/apps.py
from django.apps import AppConfig
class AdsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'ads'
def ready(self):
# This imports the signals module when Django initializes your worker threads
import ads.signals
🧠 The Operational Lifecycle Benefits
Once this is wired up, here is exactly what happens behind the scenes:
You change an ad's priority value from 4 to 10 on your custom frontend dashboard and hit "Save System Override".
Django writes the new row data to PostgreSQL.
The moment the database transaction commits, Django publishes the post_save event.
Your purge_jsdelivr_cache receiver function instantly triggers a clean execution block, hitting the purge URLs.
Your edge CDN clears its cache memory immediately.
This takes your workflow from a multi-step manual process down to a completely automated pipeline!