LoginSignup
2
2

More than 3 years have passed since last update.

Flask-Cachingを使ってPython + Flask でページキャッシュ

Last updated at Posted at 2021-01-20

Flask-Cachingを使ってPython + Flask でページキャッシュ

パッケージインストール

Flask-Cachingパッケージを使う

$ pip install Flask-Caching

Blueprint で使う方法

ディレクトリ構成
Blueprintのディレクトリ構成 の説明はこちら

weekend-hackathon/  
|-- app  
|   |-- views  
|   |    `-- sample.py  
|   |-- cache.py
|   `-- __init__.py  
|-- app.py  
|-- Dockerfile  
`-- requirements.txt 

cache.py

simple を使うとページキャッシュ、他にもmemcached、redis などがある

from flask_caching import Cache

cache = Cache(config={"CACHE_TYPE": "simple"})

__init__.py

cache.init_app(app) をすることでappにcache設定を適応

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) デコレーターを付けることで対象ページがページキャッシュになる

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"
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2