As part of an Imagino project, I designed and implemented a real-time customer consent synchronisation component. The goal: every opt-in email or SMS consent change in our Django application had to be immediately reflected in Imagino's standard tables, with no manual intervention and no batch processing. In the same compliance register, the AI Act brings its own transparency obligations to CRM.
This article details the architecture, technical decisions and watch points encountered.
The Django application hosted at the client's site provided a dedicated user interface for consent management, a communication preference form accessible to end customers directly from their personal account. This is where users activated or deactivated their email and SMS opt-ins.
Each form submission created a new entry in the ConsentLog table, with a complete change history. Imagino, in turn, needed its standard opt-in management tables to be up to date to feed email and SMS campaigns.
The requirement was clear: every new entry in ConsentLog : triggered by a user action on the interface, should push information to the Imagino API to update the corresponding customer profile in real time.
💡 Architecture decision: we chose real-time via Django signal rather than a scheduled batch. The reason: a withdrawn consent must be acted on immediately for GDPR compliance. A delay of several hours was not acceptable.
The ConsentLog table stored each consent change with its metadata:
from django.db import models
from django.db.models import Q, UniqueConstraint
from django.utils import timezone
class ConsentLog(models.Model):
# Clés d'identification, matching avec profil Imagino
email = models.EmailField(db_index=True)
nom = models.CharField(max_length=100)
prenom = models.CharField(max_length=100)
# Consentements
optin_email = models.BooleanField(default=False)
optin_sms = models.BooleanField(default=False)
# Métadonnées
created_at = models.DateTimeField(default=timezone.now)
source = models.CharField(max_length=50) # web, app, crm...
actif = models.BooleanField(default=True) # la ligne qui fait foi
class Meta:
# C'est un journal : on garde toutes les lignes, donc aucune contrainte
# d'unicité sur l'identité. Une seule ligne active par email, en
# revanche, pour savoir laquelle fait foi.
constraints = [
UniqueConstraint(
fields=['email'],
condition=Q(actif=True),
name='un_seul_consentement_actif_par_email',
),
]
indexes = [models.Index(fields=['email', '-created_at'])]
ordering = ['-created_at']
One point that needs care: ConsentLog is a journal, every change adds a row. So it cannot carry a uniqueness constraint on identity, which would stop a customer changing their mind twice. What is guaranteed is that only one row is active per email, through a conditional constraint. The email + last name + first name triplet remains the matching key used to find the profile in Imagino, but it is not a uniqueness key.
Django's post_save signal is triggered automatically after each model instance save. This is the entry point for synchronisation.
from django.db import transaction
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import ConsentLog
from .imagino_client import push_consent_to_imagino
@receiver(post_save, sender=ConsentLog)
def sync_consent_to_imagino(sender, instance, created, **kwargs):
# On ne synchronise que les nouvelles entrées
# Pas d'update, chaque changement crée un nouvel enregistrement
if not created:
return
# on_commit : l'appel ne part qu'une fois la transaction validée. Sans ça,
# un rollback laisserait Imagino avec un consentement qui n'existe pas.
transaction.on_commit(lambda: push_consent_to_imagino(instance))
💡 Key decision: we only handle creations (created=True), not updates. Each consent change creates a new row in ConsentLog : it's an immutable log, not a state table. This considerably simplifies the logic and guarantees a complete history.
The Imagino API call logic is isolated in a dedicated module, making unit testing and maintenance easier.
import requests
from django.conf import settings
from .models import ConsentLog, ErrorLogConsentAPI
IMAGINO_API_URL = settings.IMAGINO_API_URL
IMAGINO_API_KEY = settings.IMAGINO_API_KEY
def push_consent_to_imagino(consent: ConsentLog) -> None:
payload = {
"email": consent.email,
"nom": consent.nom,
"prenom": consent.prenom,
"optin_email": consent.optin_email,
"optin_sms": consent.optin_sms,
# L'horodatage permet au rejeu de ne jamais écraser un consentement
# plus récent par un plus ancien.
"consent_at": consent.created_at.isoformat(),
}
try:
response = requests.post(
f"{IMAGINO_API_URL}/consents",
json=payload,
headers={
"Authorization": f"Bearer {IMAGINO_API_KEY}",
"Content-Type": "application/json",
},
timeout=5,
)
response.raise_for_status()
except requests.RequestException as exc:
# Log de l'erreur pour traitement ultérieur
ErrorLogConsentAPI.objects.create(
consent_log = consent,
error_code = getattr(exc.response, "status_code", 0),
error_msg = str(exc),
)
Rather than raising an exception that would block the user flow, API call errors are caught and stored in a dedicated ErrorLogConsentAPI table.
class ErrorLogConsentAPI(models.Model): consent_log = models.ForeignKey( ConsentLog, on_delete=models.CASCADE, related_name='errors' ) error_code = models.IntegerField() error_msg = models.TextField() created_at = models.DateTimeField(auto_now_add=True) resolved = models.BooleanField(default=False) class Meta: ordering = ['-created_at']
This table lives on the Django side, not in Imagino: the system making the call is the one that must keep track of its failures, otherwise an API outage makes the information disappear exactly when it is needed. It lets the team see failed synchronisations at a glance, understand the cause (timeout, profile not found, duplicate…) and manually or automatically replay failed entries, without leaving the Imagino environment.
The Imagino API returns an error when the email + last name + first name triplet matches no existing profile. This is the most frequent case, a user signs up and gives consent before their profile has been created in Imagino (ingestion delay).
The solution: the error is logged with the appropriate code, and a nightly reconciliation job replays failed entries once profiles are created. Real time remains the normal path, reconciliation is only a safety net. Watch out for the replay trap: if a failed entry is replayed after a more recent consent, it overwrites the right choice with the old one. Replay therefore follows chronological order, and the timestamp sent lets the API refuse any update older than the one already recorded.
When the Imagino API detects multiple profiles matching the same identification keys (non-unique email + name triplet in Imagino), it returns a client read error. This case reveals an upstream data quality issue, duplicate profiles in Imagino that need to be merged.
A 5-second timeout is configured on each call. In case of timeout, the error is logged and the consent will be replayed during reconciliation. The user is never blocked by an Imagino API availability issue.
⚠️ Watch point: the post_save signal runs in the same thread as the Django HTTP request. A synchronous API call of up to 5 seconds can extend the response time perceived by the user. If latency is critical, consider delegating the API call to an asynchronous Celery task.
API settings never live in the code, they live in environment variables:
import os IMAGINO_API_URL = os.environ["IMAGINO_API_URL"] IMAGINO_API_KEY = os.environ["IMAGINO_API_KEY"] # os.environ[...] rather than .get(): without these variables the application # must not start. With .get() it starts and fails silently on the first # consent, which is far worse.
This real-time synchronisation architecture is simple, robust and maintainable. The Django signal does not guarantee that nothing is lost, no architecture does: what it guarantees is that every failure is logged and replayable. The error table allows tracing and replaying, and the insert-only logic considerably simplifies state management.
It works well for moderate volumes (a few dozen changes per minute). Beyond that, moving to Celery is necessary to prevent response time degradation.
I can support you on design and development. Reply within 24 hours.
Let's talk →