Flask 缓存设置方法抛出 KeyError?

The*_*uto 5 python flask flask-caching

为了缓存一些数据,我调用了 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>
Run Code Online (Sandbox Code Playgroud)

服务器模块如下所示:

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")
Run Code Online (Sandbox Code Playgroud)

和 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.")
Run Code Online (Sandbox Code Playgroud)

注意:我已经删除了不必要的代码。

我还放置了断点,并在服务器模块本身中调用了 cache.set(some_key, some_value) 。它返回 True,但相同的缓存对象在 SomeRouter 模块中导入和使用时抛出 KeyError 。会不会是我导入对象的方式不对?我还尝试在使用缓存对象之前导入它,但它不起作用。知道这里发生了什么吗?

The*_*uto 4

问题是我正在访问cache请求上下文之外的对象"SomeRouter",即模块中的对象,因此它不知道在哪个上下文下使用它。

server收到请求的模块中,缓存知道应用程序应用程序,但在cache.set(cKey, data)模块中SomeRouter,它会抛出 KeyError。如上所述,该错误是合理的。

解决方案是推送应用程序上下文,如下所示:

from server import app, cache

# Using context
with app.app_context():
    cache.set(cKey, data)
Run Code Online (Sandbox Code Playgroud)

这将推送一个新的应用程序上下文(使用应用程序的应用程序)。

全部感谢Mark Hildreth,他对Flask 中的上下文给出了很好的回答