我在蓝图上有很多路线都是按照这些路线做的:
# charts.py
@charts.route('/pie')
def pie():
# ...
return jsonify(my_data)
数据来自 CSV,每 x 小时由一个独立于应用程序的脚本抓取一次。应用程序使用一个类来读取它,然后绑定(bind)到蓝图。
# __init__.py
from flask import Blueprint
from helpers.csv_reader import CSVReader
chart_blueprint = Blueprint('chart_blueprint', __name__)
chart_blueprint.data = CSVReader('statistics.csv')
from . import charts
我的目标是缓存路由的几个响应,因为数据不会改变。然而,更具挑战性的问题是能够在我的提取脚本完成时明确清除数据。
人们会怎么做呢?我有点迷茫,但我想我需要在我的蓝图上注册一个 before_request
请您参考如下方法:
ETag and Expires正是为此而生:
class CSVReader(object):
def read_if_reloaded(self):
# Do your thing here
self.expires_on = self.calculate_next_load_time()
self.checksum = self.calculate_current_checksum()
@charts.route('/pie')
def pie():
if request.headers.get('ETag') == charts.data.checksum:
return ('', 304, {})
# ...
response = jsonify(my_data)
response.headers['Expires'] = charts.data.expires_on
response.headers['ETag'] = charts.data.checksum
return response
