Rewrite cache decorator to use format string

This is easier to read than having to understand the arguments 1…n of
the cache decorator are ‘magic’, and gives us more flexibility about
how the cache keys are formatted, eg being able to add words in the
middle of them.

Also changes the key format for all templates to be
`service-{service_id}-templates` instead of `templates-{service_id}`
because then it’s clearer what the ID represents.
This commit is contained in:
Chris Hill-Scott
2018-04-20 16:32:02 +01:00
parent b28e8691a6
commit 06de94f1c5
6 changed files with 80 additions and 91 deletions

View File

@@ -7,13 +7,14 @@ from inspect import signature
TTL = int(timedelta(hours=24).total_seconds())
def _get_argument(argument_name, args, kwargs, client_method):
def _get_argument(argument_name, client_method, args, kwargs):
with suppress(KeyError):
return kwargs[argument_name]
with suppress(ValueError, IndexError):
return args[list(signature(client_method).parameters).index(argument_name) - 1]
argument_index = list(signature(client_method).parameters).index(argument_name)
return args[argument_index - 1] # -1 because `args` doesnt include `self`
with suppress(KeyError):
return signature(client_method).parameters[argument_name].default
@@ -23,32 +24,20 @@ def _get_argument(argument_name, args, kwargs, client_method):
))
def list_of_strings(list_of_stuff):
return list(map(str, filter(None, list_of_stuff)))
def _make_key(key_format, client_method, args, kwargs):
return key_format.format(**{
argument_name: _get_argument(argument_name, client_method, args, kwargs)
for argument_name in list(signature(client_method).parameters)
})
def _make_key(prefix, key_from_args, local_variables):
return '-'.join(
[
local_variables['prefix']
] + list_of_strings(
_get_argument(
argument_name,
local_variables['args'],
local_variables['kwargs'],
local_variables['client_method']
) for argument_name in key_from_args
)
)
def set(prefix, *key_from_args):
def set(key_format):
def _set(client_method):
@wraps(client_method)
def new_client_method(client_instance, *args, **kwargs):
redis_key = _make_key(prefix, key_from_args, locals())
redis_key = _make_key(key_format, client_method, args, kwargs)
cached = client_instance.redis_client.get(redis_key)
if cached:
return json.loads(cached.decode('utf-8'))
@@ -64,13 +53,13 @@ def set(prefix, *key_from_args):
return _set
def delete(prefix, *key_from_args):
def delete(key_format):
def _delete(client_method):
@wraps(client_method)
def new_client_method(client_instance, *args, **kwargs):
redis_key = _make_key(prefix, key_from_args, locals())
redis_key = _make_key(key_format, client_method, args, kwargs)
client_instance.redis_client.delete(redis_key)
return client_method(client_instance, *args, **kwargs)