Created
September 17, 2015 20:20
-
-
Save lavagetto/ff4ae713e6e4d9d82ab1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import etcd | |
import time | |
class CachedToken(object) | |
TTL = 90*86400 | |
key = '/eventlogging/ip_hash' | |
def __init__(self, ...): | |
self.c = etcd.Client(..) | |
self.get() | |
def get(self): | |
try: | |
res = self.c.read(key) | |
except etcd.EtcdKeyNotFound: | |
res = self._set() | |
self.last_valid = time.time() + res.ttl | |
self._key = res.value | |
@property | |
def token(self): | |
t = time.time() | |
if self.last_valid < t: | |
self.get() | |
return self._key | |
def _set(self): | |
token = some_random_func() | |
try: | |
self.c.write(key, token, ttl=self.TTL, prevExist=False) | |
except etcd.EtcdAlreadyExist as e: | |
pass | |
return self.c.read(key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment