python / intermediate
Snippet
Failsafe Signal Handler with Exception Isolation and Logging
Django signals execute synchronously within the database transaction lifecycle unless explicitly offloaded. Wrapping receiver logic inside exception handling blocks prevents signal failures from aborting the primary database save operation.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import loggingfrom django.db.models.signals import post_savefrom django.dispatch import receiverfrom django.contrib.auth.models import Userlogger = logging.getLogger(__name__)@receiver(post_save, sender=User)def initialize_user_profile(sender, instance, created, **kwargs):if not created:returntry:# Imagine an external service call or database creationlogger.info(f"Triggered profile creation sequence for user ID: {instance.pk}")except Exception as exc:logger.error(f"Failed user initialization signal handler for ID {instance.pk}: {exc}", exc_info=True)
django
Breakdown
1
@receiver(post_save, sender=User)
Registers the receiver function to respond automatically whenever a User model instance is saved.
2
if not created:
Ensures heavy execution logic only runs upon new record creation rather than updates.
3
try:
Isolates the signal payload execution to prevent external downstream failures from bubbling up.
4
logger.error(f"Failed user initialization signal handler for ID {instance.pk}: {exc}", exc_info=True)
Logs full traceback details without re-raising exception, preserving main process flow.