pythonflaskflask-cacheflask-caching

How to use flask-caching in my structure of project


My code structure. I tried but kept getting error cannot import name 'caching'. I guess my method isn't correct as caching will not have app initiation when I import caching in external file.

xyz
  -app.py
  -run.py
  -urls
    -v2.py
  -resource
    -views.py
  -external.py

run.py

from app import create_app
if __name__ == "__main__":
    career_app = create_app()
    career_app.run(host=HOST,
                   port=PORT,
                   debug=True)

app.py

from flask import Flask
from flask_caching import Cache
caching = Cache(config={'CACHE_TYPE': 'simple'})
def create_app():
    """Create web app."""
    app = Flask(__name__)
    configure_app(app)
    caching.init_app(app)
    setup_blueprints(app)
    return app

external.py

from app import caching

v1.py

v2_api.add_resource(UserConfigView, '/user/config',
                    endpoint='user_config_view')

Solution

  • It is a simple factory app setup

    ext.py

    from flask_caching import Cache
    cache = Cache()
    

    app.py

    def create_app():
        app = Flask(__name__)
        register_extensions(app)
        ...
    
    def register_extensions(app):
        cache.init_app(app, config=settings.params.CACHE_CONFIG)