Use the Flask-Caching package
$ pip install Flask-Caching
Directory structure Click here for a description of the Blueprint directory structure (https://qiita.com/morita-toyscreation/items/8471a2ccc481a840c372)
weekend-hackathon/
|-- app
| |-- views
| | `-- sample.py
| |-- cache.py
| `-- __init__.py
|-- app.py
|-- Dockerfile
`-- requirements.txt
cache.py
Use simple
for page cache, memcached, redis, etc.
from flask_caching import Cache
cache = Cache(config={"CACHE_TYPE": "simple"})
__init__.py
Apply cache settings to app by doing cache.init_app (app)
from flask import Flask
from app.cache import cache
from app.views.about import about
from app.views.main import main
def get_app() -> Flask:
app = Flask(__name__)
cache.init_app(app)
_register_blueprint(app)
return app
def _register_blueprint(app: Flask) -> None:
app.register_blueprint(about)
app.register_blueprint(main)
sample.py
@ cache.cached (timeout = 50)
By adding a decorator, the target page becomes a page cache.
from flask import Blueprint
from app.cache import cache
sample = Blueprint("sample", __name__)
@sample.route("/")
@cache.cached(timeout=50)
def index():
print("sample.index")
return "sample.index"
Recommended Posts