为了避免在所有实例之间共享缓存(这可能不是必需的或所需的),最好为每个实例都有一个带有到期时间等的缓存。换句话说,我们不需要为所有实例都有“单一源缓存”。
在下面的实现中,类的每个实例都初始化自己的缓存
dict()
以存储令牌、其到期时间和其他相关信息,这将赋予您完全的控制权。
from functools import wraps
import time
class TokenCacheDecorator:
def __init__(self, get_token_func):
self.get_token_func = get_token_func
def __get__(self, inst, owner):
if inst is None:
return self
@wraps(self.get_token_func)
def wrapper(*args, **kwargs):
if not hasattr(inst, '_token_cache') or inst._token_cache['expiration_time'] < time.time():
print(f"[{id(inst)}] Cache miss")
token, expires_in = self.get_token_func(inst, *args, **kwargs)
inst._token_cache = {
'token': token,
'expiration_time': time.time() + expires_in
}
print(f"[{id(inst)}] New token - {token} expiration time: {inst._token_cache['expiration_time']}")
return inst._token_cache['token']
return wrapper
class ClassA:
def __init__(self, token, expires_in):
self.token = token
self.expires_in = expires_in
self._token_cache = {'token': None, 'expiration_time': 0}
@TokenCacheDecorator
def get_token(self):
return self.token, self.expires_in
inst1 = ClassA("token1", 2)
inst2 = ClassA("token2", 2)
inst3 = ClassA("token3", 2)
print(inst1.get_token())
print(inst2.get_token())
print(inst3.get_token())
time.sleep(3)
print(inst1.get_token())
print(inst2.get_token())
print(inst3.get_token())
打印
[4439687776] Cache miss
[4439687776] New token - token1 expiration time: 1716693215.503801
token1
[4440899024] Cache miss
[4440899024] New token - token2 expiration time: 1716693215.503846
token2
[4440899360] Cache miss
[4440899360] New token - token3 expiration time: 1716693215.503862
token3
[4439687776] Cache miss
[4439687776] New token - token1 expiration time: 1716693218.5076532
token1
[4440899024] Cache miss
[4440899024] New token - token2 expiration time: 1716693218.50767
token2
[4440899360] Cache miss
[4440899360] New token - token3 expiration time: 1716693218.507679
token3