Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask caching multiple files in project

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
like image 843
Quba Avatar asked Feb 02 '18 08:02

Quba


1 Answers

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'})
like image 158
Quba Avatar answered Oct 24 '22 06:10

Quba