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:
2026-08-30 08:46:11 +03:30
parent ff57adbc5f
commit d25ecab0b3
4 changed files with 130 additions and 7 deletions

View File

@@ -8,3 +8,4 @@ class AccountsConfig(AppConfig):
def ready(self):
# Registers OpenApiAuthenticationExtension for the Swagger UI Authorize button.
from . import schema # noqa: F401
from . import receivers # noqa: F401 (باطل‌کردنِ کشِ ردیفِ کاربر)