我想使用 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/