【发布时间】:2021-09-10 20:51:16
【问题描述】:
我将 Django 与 docker 一起使用 - 在我的 Docker-compose 中,我创建了一个 memcached 服务:
memcached:
build:
context: .
dockerfile: memcached.Dockerfile
ports:
- '11211:11211'
expose:
- "11211"
Dockerfile 看起来像这样:
FROM Memcached: latest
USER root
RUN apt-get update && apt-get install -y \
telnet \
telnetd \
libmemcached-tools \
netcat
USER memcache
EXPOSE 11211
现在缓存位置在 settings.py 中定义,它从 .ENV 文件中检索它:
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
实际的缓存函数被包装并用作注解:
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
现在代码运行良好,memcached 似乎运行良好。 我还在缓存函数中打印了日志,显示系统从缓存中获取数据。 但是当我尝试使用
memcdump --servers=localhost
我得到一个 END 答案。 当我对容器进行统计时,
STAT curr_items 0
STAT total_items 0
我对此持真正的隧道视野,并且会为每一个建议感到高兴
【问题讨论】:
标签: python django docker memcached