python django 从命令加载缓存 TfidfVectorizer 并在 View 中使用

标签 python django caching

我想使用 Django 命令加载 TfidfVectorizer 拟合模型,然后在 View 中重用它。所以在命令中

from django.core.cache import cache
from sklearn.feature_extraction.text import TfidfVectorizer
class Command(BaseCommand):
    ....
    model = TfidfVectorizer()
    modelfitted  = model.fit(data)
    cache.set('model',modelfitted)

然后在 views.py 中我想调用它:

def test_function(request):
    mod = cache.get('model')

'mod' 对象是 None。有什么想法吗?

最佳答案

问题是您正在使用本地内存缓存。如 docs 中所述此缓存是每个进程:

Note that each process will have its own private cache instance, which means no cross-process caching is possible. This obviously also means the local memory cache isn’t particularly memory-efficient, so it’s probably not a good choice for production environments. It’s nice for development.

因此不能在管理命令中写入缓存,然后在您的 runserver 进程中调用该值。

例如,您应该将缓存后端更改为文件系统缓存

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/var/tmp/django_cache',
    }
}

关于python django 从命令加载缓存 TfidfVectorizer 并在 View 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35925448/

相关文章:

php - 如何保持memcache与mysql同步?

c# - 如何检查 System.Runtime.Caching.ObjectCache 中的缓存策略?

python - 如何在python中将8位希伯来语转换为utf-8

python - Visual Studio 代码交互式 Python 控制台

c++ - Python 的 xml.etree.ElementTree 相当于 C++ XML 库

mysql - 如何在 Django 中查询时减少数据库命中次数

javascript - JQuery:Ajax 缓存 - 性能?

python - Django 在 AWS 上安装失败

javascript - 如何使用 Javascript 提交 Django 表单?

django-filebrowser 无法访问并抛出 404