Browse Source

signals for clearing cache after delete/save instances.

master
Mohsen Taba 5 months ago
parent
commit
211a64e201
  1. 3
      apps/hadis/apps.py
  2. 33
      apps/hadis/signals.py
  3. 2
      apps/hadis/urls.py
  4. 17
      config/settings/base.py

3
apps/hadis/apps.py

@ -4,3 +4,6 @@ from django.apps import AppConfig
class HadisConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.hadis'
def ready(self):
# Import the signals module when the app starts
import apps.hadis.signals

33
apps/hadis/signals.py

@ -0,0 +1,33 @@
# hadith_app/signals.py
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.core.cache import cache
from .models import *
# 1. Define all models that affect the list
# If a Category title changes, the list must update.
# If a Status changes, the list must update.
TARGET_MODELS = [Hadis , HadisCategory , HadisCollection , HadisCorrection , HadisInCollection , HadisReference ,
HadisSect , HadisStatus , HadisTag , HadisTransmitter , Transmitters ,TransmitterOpinion , TransmitterReliability,
TransmitterOriginalText,ReferenceImage , BookReference , BookAttribute, BookAuthor ,BookReferenceImage,
NarratorLayer , OpinionStatus ]
@receiver(post_save)
@receiver(post_delete)
def clear_hadis_cache(sender, instance, **kwargs):
"""
Clears the API cache whenever a Hadith or related model is saved/deleted.
"""
if sender in TARGET_MODELS:
# This is the magic command from django-redis
# It finds ALL keys starting with the prefix and deletes them
# *:1: is the default django version prefix
try:
# Delete any key that contains our prefix "hadis_api"
# The pattern "*hadis_api*" ensures we catch all variations (headers, pages, etc)
cache.delete_pattern("*hadis_api*")
print(f"Cache cleared for {sender.__name__} update!")
except Exception as e:
# Fail silently or log error, don't crash the save transaction
print(f"Cache clear failed: {e}")

2
apps/hadis/urls.py

@ -9,7 +9,7 @@ from django.views.decorators.vary import vary_on_headers
# Helper function to avoid ugly nesting
def cached_view(view_func):
return cache_page(60*60*2)(vary_on_headers('Accept-Language')(view_func))
return cache_page(60*60*2,key_prefix='hadis_api')(vary_on_headers('Accept-Language')(view_func))
urlpatterns = [

17
config/settings/base.py

@ -959,3 +959,20 @@ UNFOLD_STUDIO_DEFAULT_FRAGMENT = "color-schemes"
UNFOLD_STUDIO_PERMISSION = lambda request: request.user.is_authenticated
PLAUSIBLE_DOMAIN = env("PLAUSIBLE_DOMAIN")
# uncomment it just to check if redis caches and signals works fine locally
# CACHES = {
# 'default': {
# "BACKEND": "django_redis.cache.RedisCache",
# "LOCATION": "redis://127.0.0.1:6379/1",
# "OPTIONS": {
# "CLIENT_CLASS": "django_redis.client.DefaultClient",
# }
# },
# 'memory': {
# 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
# 'LOCATION': 'unique-snowflake',
# 'TIMEOUT': 5000,
# },
# }
Loading…
Cancel
Save