简体   繁体   English

如何使用Python(django)将文件存储在内存中?

[英]How to store a file in memory with Python (django)?

I have this code: NNModel.py 我有以下代码:NNModel.py

import pickle
from keras.models import load_model

def load_obj(name):
    with open('/home/user/' + name + '.pkl', 'rb') as f:
        return pickle.load(f)

def load_stuff():
    model = load_model("/home/user/model2.h5")
    voc = load_obj('voc')
    return (model,voc)

It loads my files when I use this function, I'd like to load them to some static or singleton ?class? 使用此功能时,它会加载我的文件,我想将它们加载到某些静态或单例类中? on the first time and then access that file. 第一次访问该文件。 How can I achieve that in Python/django? 如何在Python / Django中实现呢?

This file is fairly big and right now I belive every request loads it into memory which is not efficient I guess... 这个文件相当大,现在我相信每个请求都将其加载到内存中,我猜这效率不高...

It sounds as though you want to cache the load of the expensive file so it doesn't need to be reloaded on each subsequent request. 听起来好像您要缓存昂贵文件的加载,因此不需要在每个后续请求中重新加载它。 You could use Django's caching framework to achieve that. 您可以使用Django的缓存框架来实现。

Ensure that you have the cache configuration specified in your settings.py . 确保您具有settings.py指定的缓存配置。 For example, if you're using memcache: 例如,如果您使用的是memcache:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
        'LOCATION': 'localhost:11211',
    }
}

And then in your code, you can ask the cache for the file before you try to load it: 然后在代码中,您可以在尝试加载文件之前向缓存请求文件:

from django.core.cache import cache

def load_obj(name):
    with open('/home/user/' + name + '.pkl', 'rb') as f:
        return pickle.load(f)

def load_stuff():
    model = load_model("/home/user/model2.h5")

    voc = cache.get('my_files_cache_key')
    if voc is None:
        voc = load_obj('voc')
        cache.set('my_files_cache_key', voc, 600)

    return (model,voc)

The above example will cache the value of voc for 10 minutes (600 seconds). 上面的示例将把voc的值缓存10分钟(600秒)。

See https://docs.djangoproject.com/en/2.0/topics/cache/ for more details on setting up and using Django's cache framework. 有关设置和使用Django的缓存框架的更多详细信息,请参见https://docs.djangoproject.com/en/2.0/topics/cache/

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

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