Flask cache set method throwing KeyError?

前端 未结 1 1499
借酒劲吻你
借酒劲吻你 2021-01-19 04:48

In order to cache some data, I am calling cache.set method. However it is throwing KeyError. The error log:

 File \"D:\\Sample_Project\\SomeRouter.py\", line         


        
相关标签:
1条回答
  • 2021-01-19 05:42

    The problem was I was accessing cache object outside request context i.e. in "SomeRouter" module, and because of which it was unaware that under which context it is been used.

    In server module where request has been received, the cache knows about the app application, but during cache.set(cKey, data) in SomeRouter module, it throws KeyError. This error is justified as mentioned above.

    The resolution is to push the application context as below:

    from server import app, cache
    
    # Using context
    with app.app_context():
        cache.set(cKey, data)
    

    This will push a new application context (using the application of app).

    All thanks to Mark Hildreth, for his great answer on context in flask

    0 讨论(0)
提交回复
热议问题