具有Flask-Caching的Python Flask中的页面缓存


具有Flask-Caching的Python Flask中的页面缓存

软件包安装

使用Flask-caching软件包

1
$ pip install Flask-Caching

如何与蓝图

一起使用

目录结构
单击此处以获取蓝图目录结构的说明

1
2
3
4
5
6
7
8
9
weekend-hackathon/  
|-- app  
|   |-- views  
|   |    `-- sample.py  
|   |-- cache.py
|   `-- __init__.py  
|-- app.py  
|-- Dockerfile  
`-- requirements.txt

cache.py

simple具有页面缓存,memcached,redis等。

1
2
3
from flask_caching import Cache

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

__init__.py

通过执行

cache.init_app(app)

将缓存设置应用于应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)通过附加装饰器,目标页面将成为页面缓存

1
2
3
4
5
6
7
8
9
10
11
12
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"