|
|
|
@ -21,15 +21,19 @@ CACHE = pylru.lrucache(CACHE_SIZE)
|
|
|
|
|
# but in the file cache
|
|
|
|
|
MIN_SIZE_FOR_FILECACHE = 80
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _update_answer(answer):
|
|
|
|
|
def _now_in_tz(timezone):
|
|
|
|
|
return datetime.datetime.now(pytz.timezone(timezone)).strftime("%H:%M:%S%z")
|
|
|
|
|
|
|
|
|
|
if isinstance(answer, str) and "%{{NOW(" in answer:
|
|
|
|
|
answer = re.sub(r"%{{NOW\(([^}]*)\)}}", lambda x: _now_in_tz(x.group(1)), answer)
|
|
|
|
|
answer = re.sub(
|
|
|
|
|
r"%{{NOW\(([^}]*)\)}}", lambda x: _now_in_tz(x.group(1)), answer
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_signature(user_agent, query_string, client_ip_address, lang):
|
|
|
|
|
"""
|
|
|
|
|
Get cache signature based on `user_agent`, `url_string`,
|
|
|
|
@ -48,11 +52,11 @@ def get_signature(user_agent, query_string, client_ip_address, lang):
|
|
|
|
|
if ":" in location:
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
signature = "%s:%s:%s:%s" % \
|
|
|
|
|
(user_agent, query_string, client_ip_address, lang)
|
|
|
|
|
signature = "%s:%s:%s:%s" % (user_agent, query_string, client_ip_address, lang)
|
|
|
|
|
print(signature)
|
|
|
|
|
return signature
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get(signature):
|
|
|
|
|
"""
|
|
|
|
|
If `update_answer` is not True, return answer as it is
|
|
|
|
@ -77,9 +81,11 @@ def get(signature):
|
|
|
|
|
return _update_answer(value)
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _randint(minimum, maximum):
|
|
|
|
|
return random.randrange(maximum - minimum)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def store(signature, value):
|
|
|
|
|
"""
|
|
|
|
|
Store in cache `value` for `signature`
|
|
|
|
@ -95,15 +101,17 @@ def store(signature, value):
|
|
|
|
|
value_record = {
|
|
|
|
|
"val": value_to_store,
|
|
|
|
|
"expiry": time.time() + _randint(1000, 2000),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
CACHE[signature] = value_record
|
|
|
|
|
|
|
|
|
|
return _update_answer(value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _hash(signature):
|
|
|
|
|
return hashlib.md5(signature.encode("utf-8")).hexdigest()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _store_in_file(signature, value):
|
|
|
|
|
"""Store `value` for `signature` in cache file.
|
|
|
|
|
Return file name (signature_hash) as the result.
|
|
|
|
@ -128,6 +136,7 @@ def _store_in_file(signature, value):
|
|
|
|
|
f_cache.write(value)
|
|
|
|
|
return signature_hash
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _read_from_file(signature, sighash=None):
|
|
|
|
|
"""Read value for `signature` from cache file,
|
|
|
|
|
or return None if file is not found.
|
|
|
|
|