drf custom auth

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MyTokenAuthentication(TokenAuthentication):
def authenticate_credentials(self, key):
# get cache
token_cache = "token" + key
token_all = cache.get(token_cache)
if token_all:
return (token_all.user, token_all)
model = self.get_model()
try:
token = model.objects.select_related('user').get(key=key)
except model.DoesNotExist:
raise exceptions.AuthenticationFailed(_('Invalid token.'))
if not token.user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
# set cache
if token:
token_cache = 'token' + key
cache.set(token_cache, token)
return (token.user, token)

第一次 查询mysql 数据库 将结果缓存至redis 数据库中 第二次的话,同样的请求过来 直接查询缓存 大大提高查询效率,增加web网站的QPS