Closed
Description
Thank you for great library.
I am looking forward seeing it integrated as backend on Flask-Caching (#154). In the meantime I have tried to use diskcache in Flask app anyway. But I cannot get it working yet... I have created a factory:
from pathlib import Path
from diskcache import Cache
from flask import Flask
from flask import _app_ctx_stack as stack
class DiskCache:
def __init__(self, app=None, **options):
self.app = app
self.options = options
if app is not None:
self.init_app(self.app, **self.options)
def init_app(self, app: Flask, **options) -> None:
self.options = options
app.teardown_appcontext(self.teardown)
def configure_app(self, context):
directory = context.app.config.get('DISK_CACHE_DIR')
if not directory:
raise ValueError(f"Missing DISK_CACHE_DIR setting")
else:
cpath = Path( directory )
if not cpath.is_dir():
raise ValueError(f"Invalid DISK_CACHE_DIR")
return directory
def __getattr__(self, item):
context = stack.top
if context is not None:
if not hasattr(context, 'diskcache'):
directory = self.configure_app(context)
timeout = context.app.config.get('CACHE_DEFAULT_TIMEOUT', 3600)
size_limit = context.app.config.get('CACHE_THRESHOLD', 1000)
context.diskcache = Cache(directory, timeout=timeout, size_limit=size_limit, **self.options)
return getattr(context.diskcache, item)
raise RuntimeError("No Application Context")
def teardown(self, exception):
ctx = stack.top
if hasattr(ctx, 'diskcache'):
ctx.diskcache = None
Then initialize it in my extensions.py - dcache = DiskCache() and import it to main module:
from flask import Flask
from application.extensions import dcache
def create_app():
app = Flask(__name__)
dcache.init_app(app)
return app
The cache.db gets created in the appropriate directory but dcache.set(key, val) seems not working - dcache.count output 0.
I have not figured why... Any hints would be greatly appreciated.
Metadata
Metadata
Assignees
Labels
No labels