optional short-TTL cache for the auth user row
TadrisinoTokenAuthentication ran one SELECT on accounts_user for every
authenticated request. Off by default (AUTH_USER_CACHE_TTL=0) so behaviour
is unchanged until a deployment opts in.
accounts/authentication.py
- _get_request_user(): when AUTH_USER_CACHE_TTL>0, cache all concrete
field values under auth:user:<id> and rebuild a full User instance
(so save(update_fields=[...]) stays safe); otherwise load from DB as
before. invalidate_user_cache() / _load_user_or_fail() helpers.
accounts/receivers.py (new)
- post_save/post_delete on User -> invalidate_user_cache(pk); covers
every in-app write path (SetUserGrade, login, refresh, last_activity).
accounts/apps.py
- AccountsConfig.ready() imports receivers.
accounts/tests.py
- AuthUserRowCacheTests: disabled -> loads every request; enabled ->
loads once then cache; User.save() invalidates; SetUserGradeView still
persists and the next request sees the new grade.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
22
accounts/receivers.py
Normal file
22
accounts/receivers.py
Normal file
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
باطلکردنِ کشِ ردیفِ کاربر (auth:user:<id>) با هر تغییرِ User.
|
||||
|
||||
این سیگنالها همهی مسیرهای نوشتنِ داخلِ اپ (SetUserGrade، لاگین، رفرشتوکن،
|
||||
last_activity_at، ...) را پوشش میدهند؛ فقط تغییری که کاملاً بیرون از ORM
|
||||
اعمال شود (مثلاً UPDATE مستقیمِ SQL) تا سقفِ AUTH_USER_CACHE_TTL کهنه میماند.
|
||||
"""
|
||||
from django.db.models.signals import post_delete, post_save
|
||||
from django.dispatch import receiver
|
||||
|
||||
from .authentication import invalidate_user_cache
|
||||
from .models import User
|
||||
|
||||
|
||||
@receiver(post_save, sender=User, dispatch_uid='accounts_invalidate_user_cache_on_save')
|
||||
def _invalidate_on_save(sender, instance, **kwargs):
|
||||
invalidate_user_cache(instance.pk)
|
||||
|
||||
|
||||
@receiver(post_delete, sender=User, dispatch_uid='accounts_invalidate_user_cache_on_delete')
|
||||
def _invalidate_on_delete(sender, instance, **kwargs):
|
||||
invalidate_user_cache(instance.pk)
|
||||
Reference in New Issue
Block a user