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
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'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With