Flask 自己不提供緩存,可是它的基礎庫之一Werkzeug有一些很是基本的緩存支持。json
代碼:flask
from flask import Flask, request, g, current_app ,session from flask_restful import Resource, Api,reqparse import requests import json # gevent from gevent import monkey, sleep from gevent.pywsgi import WSGIServer monkey.patch_all() # gevent end import time # Cache from werkzeug.contrib.cache import SimpleCache cache = SimpleCache() # Cache End # 請求A: post,而且產生一個變量 key # 請求B: 須要用到請求A的變量key # Flask的底層——Werkzeug——是有緩存支持的 app = Flask(__name__) api = Api(app) app.config.update(DEBUG=True) # 示例1: 定義兩個路由,經過cache傳遞數據. @app.route('/asyn/', methods=['GET']) def test_asyn_one(): print("asyn has a request!") cache.clear() timeout = 30 while (not cache.has('a')) and timeout >0: sleep(1) timeout = timeout - 1 print('timeout:', timeout) print("a", cache.get('a')) return 'hello asyn' @app.route('/test/', methods=['GET']) def test(): cache.set('a', '1') return 'hello test' # 示例2: 定義flask_restful服務 # 兩個服務都是Post方法,請求地址分別是 http://locahost:5000/ttest/1 和 http://locahost:5000/ttest/2 # 用戶訪問 /ttest/1 時產生的數據, 經過cache傳遞給了用戶第二次訪問 /ttest/2 時使用. class TTest(Resource): def post(self,todo_id): if todo_id is '1': cache.clear() cache.set('a','aaaaaaaaaa') return 1 elif todo_id is '2': x = cache.get('a') return x api.add_resource(TTest, '/ttest/<string:todo_id>') if __name__ == "__main__": # app.run() http_server = WSGIServer(('', 5000), app) http_server.serve_forever()
參考api