简体   繁体   English

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

[英]python django load in cache TfidfVectorizer from command and use in view

I would like to load a TfidfVectorizer fitted model using a Django command and then reuse it on view.我想使用 Django 命令加载 TfidfVectorizer 拟合模型,然后在视图中重用它。 So in the command所以在命令中

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)

Then in views.py I would like to call it:然后在 views.py 中我想称之为:

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

the 'mod' object is None. 'mod' 对象是 None。 Any idea?任何的想法?

The problem is that you are using Local-memory caching .问题是您正在使用Local-memory caching As stated in the docs this cache is per-process :正如文档中所述,此缓存是每个进程的

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.很适合开发。

So can't write to the cache in a managemant command and then call this value in your runserver process.所以不能在管理命令中写入缓存,然后在你的runserver进程中调用这个值。

You should change you cache backend for example to Filesystem caching您应该将缓存后端更改为例如Filesystem caching

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM