# Path: src/sa_api_v2/cache.py
# class UserCache (Cache):
#     def get_instance_params(self, user_obj):
#         params = {'user_id': user_obj.id}
#         return params
# 
#     # == Raw query caching
#     @classmethod
#     def get_instance_key(cls, **params):
#         return ':'.join(['user-instance', str(params['user_id'])])
# 
#     @classmethod
#     def get_instance(cls, **params):
#         """
#         Get a full cached user instance.
#         """
#         key = cls.get_instance_key(**params)
#         return cache_buffer.get(key)
# 
#     @classmethod
#     def set_instance(cls, instance, **params):
#         key = cls.get_instance_key(**params)
#         cache_buffer.set(key, instance)
# 
#     # == Cache invalidation
#     @classmethod
#     def get_request_prefixes(cls, **params):
#         return set()
# 
#     @classmethod
#     def get_other_keys(cls, **params):
#         return set([cls.get_instance_key(**params)])


from django.contrib.auth.backends import ModelBackend
from .cache import UserCache

class CachedModelBackend (ModelBackend):
    def get_user(self, user_id):
        user = UserCache.get_instance(user_id=user_id)
        if user is None:
            user = super(CachedModelBackend, self).get_user(user_id)

# Path: src/sa_api_v2/cache.py
# class UserCache (Cache):
#     def get_instance_params(self, user_obj):
#         params = {'user_id': user_obj.id}
#         return params
# 
#     # == Raw query caching
#     @classmethod
#     def get_instance_key(cls, **params):
#         return ':'.join(['user-instance', str(params['user_id'])])
# 
#     @classmethod
#     def get_instance(cls, **params):
#         """
#         Get a full cached user instance.
#         """
#         key = cls.get_instance_key(**params)
#         return cache_buffer.get(key)
# 
#     @classmethod
#     def set_instance(cls, instance, **params):
#         key = cls.get_instance_key(**params)
#         cache_buffer.set(key, instance)
# 
#     # == Cache invalidation
#     @classmethod
#     def get_request_prefixes(cls, **params):
#         return set()
# 
#     @classmethod
#     def get_other_keys(cls, **params):
#         return set([cls.get_instance_key(**params)])


# Path: src/sa_api_v2/auth_backends.py
from django.contrib.auth.backends import ModelBackend
from .cache import UserCache


class CachedModelBackend (ModelBackend):
    def get_user(self, user_id):
        user = UserCache.get_instance(user_id=user_id)
        if user is None:
            user = super(CachedModelBackend, self).get_user(user_id)

            UserCache.set_instance(user, user_id=user_id)