如何使用 Django 在任务和视图之间共享缓存?
How to share cache between a task and a view with Django?
在我的 django 项目中,我每 5 分钟得到一个任务 运行(使用 Celery 和 Redis 作为代理):
from django.core.cache import cache
@shared_task()
@celery.task(base=QueueOnce)
def cache_date():
cache.set('date', datetime.now)
print('Cached date : ', cache.get('date'))
而且 运行 很好,每次运行时都打印新的缓存日期
但是,在我的一个观点中,我尝试这样做:
from django.core.cache import cache
def get_cached_date():
print('Cached date :', cache.get('date')
然后打印 "Cached date : None"
这是我的缓存设置:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/tmp/cache',
}
}
我不明白,为什么当我使用单个位置文件时该值在一个地方可用而在另一个地方不可用?我是不是做错了什么?
更新
@Satevg 我使用 docker-compose,这是我的文件:
services:
redis:
image: redis
worker:
image: project
depends_on:
- redis
- webserver
command: project backend worker
volumes:
- cache:/tmp/cache
webserver:
image: project
depends_on:
- redis
volumes:
- cache:/tmp/cache
volumes:
cache:
我尝试像这样共享卷,但是当我的任务尝试写入缓存时,我得到:
OSError: [Errno 13] Permission denied: '/tmp/cache/tmpAg_TAc'
当我查看两个容器中的文件系统时,我可以看到文件夹 /tmp/cache,Web 应用程序甚至可以在上面写入,当我查看 worker 的容器 /tmp/cache 文件夹时,我可以看到更新的缓存
更新2:
webapp 可以写入缓存。
cache.set('test', 'Test')
在 worker 的容器上,我可以在 /tmp/cache 文件夹中看到缓存文件
当任务尝试从缓存中读取时:
print(cache.get('test'))
它说:
None
当任务尝试从缓存写入时,它仍然得到 Errno13
正如我们在评论中发现的那样,celery 和应用程序在不同的 docker 容器中工作。
django.core.cache.backends.filebased.FileBasedCache
将每个缓存值序列化并存储为单独的文件。但是这些文件位于不同 个文件系统中。
解决方案是使用 docker volumes 以便在这两个容器之间共享 /tmp/cache
文件夹。
在我的 django 项目中,我每 5 分钟得到一个任务 运行(使用 Celery 和 Redis 作为代理):
from django.core.cache import cache
@shared_task()
@celery.task(base=QueueOnce)
def cache_date():
cache.set('date', datetime.now)
print('Cached date : ', cache.get('date'))
而且 运行 很好,每次运行时都打印新的缓存日期
但是,在我的一个观点中,我尝试这样做:
from django.core.cache import cache
def get_cached_date():
print('Cached date :', cache.get('date')
然后打印 "Cached date : None"
这是我的缓存设置:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/tmp/cache',
}
}
我不明白,为什么当我使用单个位置文件时该值在一个地方可用而在另一个地方不可用?我是不是做错了什么?
更新
@Satevg 我使用 docker-compose,这是我的文件:
services:
redis:
image: redis
worker:
image: project
depends_on:
- redis
- webserver
command: project backend worker
volumes:
- cache:/tmp/cache
webserver:
image: project
depends_on:
- redis
volumes:
- cache:/tmp/cache
volumes:
cache:
我尝试像这样共享卷,但是当我的任务尝试写入缓存时,我得到:
OSError: [Errno 13] Permission denied: '/tmp/cache/tmpAg_TAc'
当我查看两个容器中的文件系统时,我可以看到文件夹 /tmp/cache,Web 应用程序甚至可以在上面写入,当我查看 worker 的容器 /tmp/cache 文件夹时,我可以看到更新的缓存
更新2:
webapp 可以写入缓存。
cache.set('test', 'Test')
在 worker 的容器上,我可以在 /tmp/cache 文件夹中看到缓存文件 当任务尝试从缓存中读取时:
print(cache.get('test'))
它说:
None
当任务尝试从缓存写入时,它仍然得到 Errno13
正如我们在评论中发现的那样,celery 和应用程序在不同的 docker 容器中工作。
django.core.cache.backends.filebased.FileBasedCache
将每个缓存值序列化并存储为单独的文件。但是这些文件位于不同 个文件系统中。
解决方案是使用 docker volumes 以便在这两个容器之间共享 /tmp/cache
文件夹。