I'm using Django with docker - In my Docker-compose I created a memcached service:
memcached:
build:
context: .
dockerfile: memcached.Dockerfile
ports:
- '11211:11211'
expose:
- "11211"
the Dockerfile looks like this:
FROM Memcached: latest
USER root
RUN apt-get update && apt-get install -y \
telnet \
telnetd \
libmemcached-tools \
netcat
USER memcache
EXPOSE 11211
Now the cache location is defined in settings.py which retrieves it from .ENV file :
settings.py
if os.getenv("CACHE_BACKEND"):
cache_timeout = os.getenv("CACHE_TIMEOUT")
CACHES = {
'default': {
'BACKEND': os.getenv("CACHE_BACKEND"),
'LOCATION': os.getenv("CACHE_LOCATION"),
'TIMEOUT': None
}
}
.env
CACHE_BACKEND = django.core.cache.backends.memcached.MemcachedCache
CACHE_LOCATION = ***********:11211 # I covered the container name
CACHE_TIMEOUT = None
the actual caching function is wrapped and uses as an annotation:
def caching(code_version=None):
"""
Decorator with argument
:param code_version: code version from DB
:return: real_decorator
"""
def real_decorator(func):
"""
Wrapper function that reads from the cache if the value already exists and if not then it
saves it to the cache
:param func: wrapped function
:return: Wrapper function
"""
def func_wrapper(request):
from django.http import HttpResponse
from django.core.serializers.json import DjangoJSONEncoder
from django.core.cache import cache
if code_version:
cache.version = code_version
url = request.get_full_path()
url_hash = f"{abs(hash(url))}"
save_cache: bool = len(url_hash) <= 250
print(f"SAVE CACHE-----------------------{save_cache}")
if save_cache:
try:
cache_result = cache.get(url_hash)
if cache_result:
print(f"\n\n\nHello my name is {url} ,& I'm A memcached user")
return HttpResponse(cache_result)
except Exception as e:
print(e)
data = json.dumps(func(request), cls=DjangoJSONEncoder)
if save_cache:
print(f"\n\n\nHello my name is {url} ,& I'm A memcached pusher------------------------{url_hash}-----------{cache}--------")
try:
cache.set(url_hash, data)
except Exception as e:
print(e)
return HttpResponse(data)
return func_wrapper
return real_decorator
now the code is working well, and it appears that the memcached is working fine. I also printed logs in the caching function that shows me that the system gets its data from the cache. but when I'm trying to use the
memcdump --servers=localhost
I get an END answer. when I'm stats over the container the
STAT curr_items 0
STAT total_items 0
I'm in real tunnel vision about it and will be happy for every suggestion