Flask缓存机制 #
一、Flask-Caching #
1.1 安装 #
bash
pip install flask-caching
1.2 配置 #
python
from flask_caching import Cache
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'SimpleCache'
cache = Cache(app)
二、缓存类型 #
| 类型 | 说明 |
|---|---|
| SimpleCache | 内存缓存 |
| RedisCache | Redis缓存 |
| MemcachedCache | Memcached缓存 |
三、使用缓存 #
3.1 缓存视图 #
python
@app.route('/expensive')
@cache.cached(timeout=60)
def expensive_operation():
return '计算结果'
3.2 缓存函数 #
python
@cache.memoize(timeout=60)
def get_user(user_id):
return User.query.get(user_id)
3.3 手动缓存 #
python
@app.route('/data')
def get_data():
data = cache.get('my_data')
if data is None:
data = compute_expensive_data()
cache.set('my_data', data, timeout=60)
return data
四、下一步 #
接下来让我们学习 异步任务,了解后台任务处理!
最后更新:2026-03-28