为了缓存一些数据,我正在调用 cache.set 方法。但是它正在抛出 KeyError。错误日志:
File "D:\Sample_Project\SomeRouter.py", line 176, in run
FetchFeed._prepareCache(f_content, cache, _program, _sprint)
File "D:\Sample_Project\SomeRouter.py", line 197, in _prepareCache
cache.set(cKey, data[last_index:last_index + MAX_DATA_PER_PAGE])
File "c:\python\lib\site-packages\flask_caching\__init__.py", line 254, in set
return self.cache.set(*args, **kwargs)
File "c:\python\lib\site-packages\flask_caching\__init__.py", line 246, in cache
return app.extensions["cache"][self]
KeyError: <flask_caching.Cache object at 0x04F9C8D0>
服务器模块如下所示:
cache_type = 'simple' if 'FLASK_ENV' in os.environ and os.environ['FLASK_ENV'] == 'development' else 'uwsgi'
cache = Cache(config={'CACHE_TYPE': cache_type})
app = Flask("MY_PROJECT")
cache.init_app(app)
# some api.route functions
# goes here ....
if __name__ == "__main__":
with app.app_context():
cache.clear()
app.run(host="0.0.0.0")
和 SomeRouter 模块:
from server import cache
@staticmethod
def _prepareCache(data, cache, program):
total_records = len(data)
if total_records > 0:
cKey = FetchFeed \
._constructCacheKey(program)
cache.set(cKey, data)
else:
print("data size is empty.")
注意:我已经删除了不必要的代码。
我还设置了断点,并在服务器模块本身中调用了 cache.set(some_key, some_value)。它返回 True,但在 SomeRouter 模块中导入和使用时,相同的缓存对象会抛出 KeyError。难道是我导入对象的方式是错误的?我也尝试在使用它之前导入缓存对象,但它不起作用。知道这里发生了什么吗?