目录
原文:python flask-caching模块缓存详解_ghostwritten的博客-CSDN博客_flask-caching
- # ---coding:utf-8
- from flask import Flask, request
- from flask_caching import Cache
-
- app = Flask(__name__)
- # simple使用字典存储
- cache = Cache(app, config={'CACHE_TYPE': 'simple'})
-
- @app.route('/index')
- @cache.cached(timeout=20)
- def index():
- print(request.path)
- s = 'test cache'
- cache.set('b', 123)
- print('test cache')
-
- return s
-
-
- @app.route('/test')
- def test():
- print(cache.get('b'))
- return 'ok'
-
-
- if __name__ == '__main__':
- app.run(host='0.0.0.0')
这样在访问127.0.0.1/index时就缓存了一个{"b":123}
通过访问127.0.0.1/test取出缓存的{"b":123}
主要是通过多进程模块的消息队列来缓存
- # ---coding:utf-8
- from flask import Flask, request
- from flask_caching import Cache
- import multiprocessing
-
- app = Flask(__name__)
- queue = multiprocessing.Queue(5)
-
- @app.route('/index')
- def index():
- queue.put(111)
- return "ok"
-
-
- @app.route('/test')
- def test():
- string = str(queue.get())
- return string
-
-
- if __name__ == '__main__':
- app.run(host='0.0.0.0')
这样每次在访问127.0.0.1/index时就向消息队列(queue)放入了一个111
通过访问127.0.0.1/test按顺序取出queue的值,如果queue的值取完了,就会处于阻塞状态,直到有新的值进入queue
比如访问一次127.0.0.1/index,访问两次127.0.0.1/test,那么当第二次访问127.0.0.1/test时此接口处于阻塞状态(一直不会有响应)。原因是queue中只有一个值,取第二次时就会在一直等待,如果此时再访问127.0.0.1/index,则此时queue由有值了,那么127.0.0.1/test就会立马有响应了。