· 7 years ago · Oct 07, 2018, 06:26 PM
1from hashlib import md5
2from django.db.models import Q
3from django.core.cache import cache
4from piston.models import Consumer, Token
5from piston.store import DataStore as PistonDataStore
6from model_cache import ModelCache
7
8
9consumer_cache = ModelCache(Consumer)
10token_cache = ModelCache(Token)
11
12
13class CachedOAuthDataStore(PistonDataStore):
14 def lookup_consumer(self, key):
15 self.consumer = consumer_cache(Q(key=key))
16 self.consumer.key = self.consumer.key.encode('ascii')
17 self.consumer.secret = self.consumer.secret.encode('ascii')
18 return self.consumer
19
20 def lookup_token(self, token_type, token):
21 if token_type == 'request':
22 token_type = Token.REQUEST
23 elif token_type == 'access':
24 token_type = Token.ACCESS
25 try:
26 self.request_token = token_cache(Q(token_type=token_type,
27 key=token))
28 return self.request_token
29 except Token.DoesNotExist:
30 return None
31
32 def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
33 bits = (oauth_consumer.key + oauth_consumer.secret
34 + getattr(oauth_token, 'key', '')
35 + getattr(oauth_token, 'secret', '')
36 + nonce)
37 key = 'nonce' + md5(bits).hexdigest()
38 r = cache.get(key)
39 if not r:
40 cache.set(key, 'v', 60*60*24)
41 return None
42 return r