13

I'm relatively new to Flask. I have multiple files in my flask project. Up until now, I was using current_app if I wanted to access app object from outside of app.py file.

Now I am trying to add cache to my app with flask-caching extension. I initialize this in my app.py

from flask_caching import Cache
...
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

However I'm having troubles with uisng it with views.py file.

I have a resource class:

class MyEndpoint(Resource):
    def get(self):
        do_stuff_here

I don't know how to get cache object here to achieve this:

class MyEndpoint(Resource):
    @cache.cached(timeout=600)
    def get(self):
        do_stuff_here

I tried to do:

  • from app import cache -> ImportError: cannot import name 'cache'
  • @current_app.cache.cached -> RuntimeError: Working outside of application context.

Part of the structure of my project:

|
-app.py
|
--api
  |
  -__init__.py
  -views.py
5
  • Can you show imports of app.py and views.py? Commented Feb 28, 2018 at 14:43
  • @Quba, do you mind sharing how you ended up fixing this issue? Commented May 17, 2018 at 5:02
  • @MarcioPorto Sure. Will do that in a few hours Commented May 17, 2018 at 6:30
  • @Quba, still haven't figured out this issue. Can you give me some guidance on how to accomplish this? Commented May 21, 2018 at 5:10
  • @MarcioPorto I just posted an answer. Commented May 21, 2018 at 12:19

2 Answers 2

30

I got it working. Just initialize Cache object in a different file:

common/extensions.py:

from flask_caching import Cache

cache = Cache() 

and then in app.py:

from common.extensions import cache
app = Flask(__name__)
cache.init_app(app, config={'CACHE_TYPE': 'simple'})
Sign up to request clarification or add additional context in comments.

2 Comments

Unresolved reference 'Cache' . How to install the Cache?
Life-safer for me, too. Lol
0

I had the same issue and this was because I was registering the modules of my app before I created the cache object. This creates a cyclic dependency where the module code tries to load the cache before it is created.

Register your modules in the flask app after initializing the cache. Then from app import cache should work fine inside your modules.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.