我对使用烧瓶有点陌生,我想缓存读取腌制数据的函数的结果。我使用如下memoize
功能:flask_cache
在model_chacher.py
:
from flask_cache import Cache
import pickle
model_cache = Cache(config={'CACHE_TYPE': 'simple'})
class ModelCacher():
@model_cache.memoize(50)
def get_model(self, customer_ID):
with open('/path/to/data.pickle', 'rb') as tf:
model_args = pickle.load(tf)
trained_classifier = model_args[0]
return trained_classifier
在flask_compose.py
:
from flask import Flask
from controllers.topic import controller as topic_controller
from models.modelcache.model_chacher import model_cache
app = Flask(__name__)
model_cache.init_app(app)
app.register_blueprint(topic_controller.topic_controller_blueprint)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=80, debug=True)
我打电话ModelCacher.get_model(customer_ID)
给topic_controller
:
from models.modelcache.model_chacher import ModelCacher
...
trained_classifier = ModelCacher.get_model(cls_str)
...
在运行flask_compose.py
并发送请求后,我得到以下结果:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/app/controllers/topic/controller.py", line 20, in classify
return ModelCacher.get_model(cls_str)
File "/usr/local/lib/python3.6/site-packages/flask_cache/__init__.py", line 528, in decorated_function
cache_key = decorated_function.make_cache_key(f, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/flask_cache/__init__.py", line 393, in make_cache_key
**kwargs)
File "/usr/local/lib/python3.6/site-packages/flask_cache/__init__.py", line 434, in _memoize_kwargs_to_args
elif abs(i-args_len) <= len(argspec.defaults):
TypeError: object of type 'NoneType' has no len()
我的问题是:如何正确设置我的缓存?任何帮助是极大的赞赏。
编辑:什么解决了我的问题:
正如@stamaimer 指出的那样,我创建了我的实例ModelCacher
并解决了问题,我也使用了缓存flask_cache.Cache
而不是memoize
.