Utilizando cache de django
This commit is contained in:
@@ -77,6 +77,21 @@ DATABASES = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
"""Cache configuration"""
|
||||||
|
CACHES = {
|
||||||
|
"default": {
|
||||||
|
"BACKEND": "django_redis.cache.RedisCache",
|
||||||
|
"LOCATION": "redis://127.0.0.1:6379/1",
|
||||||
|
"OPTIONS": {
|
||||||
|
"CLIENT_CLASS": "django_redis.client.DefaultClient",
|
||||||
|
},
|
||||||
|
"KEY_PREFIX": "DJANGO_SERVER"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
|
||||||
|
SESSION_CACHE_ALIAS = "default"
|
||||||
|
|
||||||
"""How to validate password security"""
|
"""How to validate password security"""
|
||||||
AUTH_PASSWORD_VALIDATORS = [
|
AUTH_PASSWORD_VALIDATORS = [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ djangorestframework # The framework to create the api
|
|||||||
pygments # To make cute pretty prints XD
|
pygments # To make cute pretty prints XD
|
||||||
ratelimit # To rate limit request to musicbrainz
|
ratelimit # To rate limit request to musicbrainz
|
||||||
redis # To comunicate with redis
|
redis # To comunicate with redis
|
||||||
|
django-redis # Redis backend for django
|
||||||
requests # Saner request library
|
requests # Saner request library
|
||||||
blake3 # To use blake3 hashing, since python seeds every hash on hashlib and is different between instances
|
blake3 # To use blake3 hashing, since python seeds every hash on hashlib and is different between instances
|
||||||
country_list # To transform country codes to their names
|
country_list # To transform country codes to their names
|
||||||
@@ -1,15 +1,12 @@
|
|||||||
"""Modulo que contiene la clase/decorador Cache, contiene su logger y una conexión a redis"""
|
"""Modulo que contiene la clase/decorador Cache"""
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from blake3 import blake3 # pylint: disable=no-name-in-module
|
from blake3 import blake3 # pylint: disable=no-name-in-module
|
||||||
from redis import Redis
|
from django.core.cache import cache
|
||||||
from django.conf import settings
|
|
||||||
|
|
||||||
_log = logging.getLogger(__name__)
|
_log = logging.getLogger(__name__)
|
||||||
_log.addHandler(logging.NullHandler())
|
_log.addHandler(logging.NullHandler())
|
||||||
|
|
||||||
_redis = Redis()
|
|
||||||
|
|
||||||
|
|
||||||
class Cache:
|
class Cache:
|
||||||
""" Decorator that caches the result of a function
|
""" Decorator that caches the result of a function
|
||||||
@@ -21,9 +18,6 @@ class Cache:
|
|||||||
It is assumed that the function will returns a dictionary that can be formatted to json.
|
It is assumed that the function will returns a dictionary that can be formatted to json.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# If caching is enabled
|
|
||||||
enabled = settings.CUSTOM_CACHE['enabled']
|
|
||||||
|
|
||||||
# Time to expire, by default a week
|
# Time to expire, by default a week
|
||||||
expire = 60 * 60 * 24 * 7
|
expire = 60 * 60 * 24 * 7
|
||||||
|
|
||||||
@@ -31,24 +25,20 @@ class Cache:
|
|||||||
self.function = function
|
self.function = function
|
||||||
|
|
||||||
def __call__(self, *args, **kwargs):
|
def __call__(self, *args, **kwargs):
|
||||||
if not self.enabled:
|
|
||||||
_log.info('Cache is disabled, executing function directly')
|
|
||||||
return self.function(*args, **kwargs)
|
|
||||||
|
|
||||||
_log.info('Caching function %s with argument list %s and dictionary %s',
|
_log.info('Caching function %s with argument list %s and dictionary %s',
|
||||||
self.function.__name__, args, kwargs)
|
self.function.__name__, args, kwargs)
|
||||||
|
|
||||||
key = f'{self.function.__name__}:{self.create_hash_key(args, kwargs)}'
|
key = f'{self.function.__name__}:{self.create_hash_key(args, kwargs)}'
|
||||||
_log.debug('Resolved key for function is "%s"', key)
|
_log.debug('Resolved key for function is "%s"', key)
|
||||||
|
|
||||||
if _redis.exists(key):
|
if cache.ttl(key) != 0:
|
||||||
_log.info('Key was in cache')
|
_log.info('Key was in cache')
|
||||||
result = json.loads(_redis.get(key))
|
result = json.loads(cache.get(key))
|
||||||
return result
|
return result
|
||||||
|
|
||||||
_log.info('Key was not in cache')
|
_log.info('Key was not in cache')
|
||||||
result = self.function(*args, **kwargs)
|
result = self.function(*args, **kwargs)
|
||||||
_redis.set(key, json.dumps(result), ex=self.expire)
|
cache.set(key, json.dumps(result), timeout=self.expire)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
Reference in New Issue
Block a user