在 Flask 中,使用 Flask-Caching 可以显著提高应用的性能,尤其是对于计算密集型操作、数据库查询或外部 API 调用。Flask-Caching 通过存储数据的副本减少重复计算,从而加快响应速度。
首先,安装 Flask-Caching:
pip install Flask-Caching
在 Flask 应用中,配置缓存类型和参数,例如使用内存、Redis、文件系统等。
from flask import Flask, request
from flask_caching import Cache
app = Flask(__name__)
# 配置 Flask-Caching(使用简单的内存缓存)
app.config['CACHE_TYPE'] = 'SimpleCache' # 使用简单内存缓存
app.config['CACHE_DEFAULT_TIMEOUT'] = 300 # 默认缓存超时(秒)
cache = Cache(app)
@app.route('/')
@cache.cached(timeout=60) # 为此路由缓存60秒
def index():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
Flask-Caching 支持多种缓存存储后端,常见配置如下:
缓存类型 | CACHE_TYPE 值 |
依赖项 |
---|---|---|
内存缓存 | SimpleCache |
无 |
Redis 缓存 | RedisCache |
pip install redis |
文件系统缓存 | FileSystemCache |
无 |
Memcached 缓存 | MemcachedCache |
pip install pymemcache |
Null(禁用缓存) | NullCache |
无 |
app.config['CACHE_TYPE'] = 'RedisCache'
app.config['CACHE_REDIS_HOST'] = 'localhost'
app.config['CACHE_REDIS_PORT'] = 6379
app.config['CACHE_REDIS_DB'] = 0
app.config['CACHE_DEFAULT_TIMEOUT'] = 600 # 10分钟
app.config['CACHE_TYPE'] = 'FileSystemCache'
app.config['CACHE_DIR'] = '/tmp/flask_cache'
@app.route('/data')
@cache.cached(timeout=120) # 120秒缓存
def expensive_query():
import time
time.sleep(5) # 模拟耗时操作
return "Expensive data fetched!"
如果想要缓存某个函数的计算结果:
@cache.memoize(timeout=300)
def compute_expensive_result(x, y):
import time
time.sleep(5) # 模拟耗时
return x + y
@app.route('/compute')
def compute():
result = compute_expensive_result(10, 20)
return f"Computed result: {result}"
你可以通过 make_cache_key
方法让缓存基于 URL 参数变化。
@app.route('/user')
@cache.cached(timeout=60, query_string=True)
def user_profile():
username = request.args.get('name', 'Guest')
return f"Hello, {username}!"
例如:
GET /user?name=Alice
会缓存 Alice 的数据GET /user?name=Bob
会缓存 Bob 的数据cache.set('my_key', 'my_value', timeout=300) # 设置 300 秒
value = cache.get('my_key')
if value is None:
value = "New Value"
cache.set('my_key', value, timeout=300)
print(value)
cache.delete('my_key')
cache.clear()
你可以自定义缓存键,使缓存结果针对不同的用户或查询参数:
def custom_cache_key():
return request.full_path # 以完整 URL 作为缓存键
@app.route('/product')
@cache.cached(timeout=300, key_prefix=custom_cache_key)
def product():
return "Product data"
如果想要在模板中缓存某些片段,可以在视图函数内部使用缓存:
@app.route('/dashboard')
def dashboard():
stats = cache.get('dashboard_stats')
if not stats:
stats = expensive_dashboard_calculation()
cache.set('dashboard_stats', stats, timeout=600)
return render_template('dashboard.html', stats=stats)
启用 Flask 的调试模式并添加日志,以查看缓存的命中情况:
app.config['DEBUG'] = True
app.config['CACHE_TYPE'] = 'SimpleCache'
app.config['CACHE_DEFAULT_TIMEOUT'] = 60
启用 System.debug
记录缓存的操作:
import logging
logging.basicConfig(level=logging.DEBUG)
缓存未生效?
CACHE_TYPE
,并启用了 CACHE_DEFAULT_TIMEOUT
。no-cache
头,浏览器可能绕过缓存。如何处理缓存依赖变化?
cache.delete()
删除相关数据的缓存。如何避免过期导致并发请求?
使用 Flask-Caching
提升性能的关键点:
@cache.cached
或 @cache.memoize
避免重复处理。如果你需要更复杂的缓存策略,可以考虑: