1.安装flask_caching库
pip install flask_caching
2.创建utils Python 软件包以及cache_helper.py
2.1cache_helper.py代码
from flask_caching import Cache
cache = Cache()
class CacheHelper:
def __init__(self, app, config):
cache.init_app(app, config)
@staticmethod
def get(key):
return cache.get(key)
@staticmethod
def set(key, value, timeout=None):
cache.set(key, value, timeout=timeout)
@staticmethod
def delete(key):
cache.delete(key)
3.app.py文件中代码
3.1.初始化cache代码
# 初始化cache,硬编码方式配置缓存
# cache = CacheHelper(app, config={'CACHE_TYPE': 'simple'})
# 初始化cache,读取配置文件方式配置缓存
cache = CacheHelper(app, config=cache_config)
3.2.config.py完整代码如下
# 配置Cache缓存类型参数值
cache_config = {
'CACHE_TYPE': 'simple' # 使用本地python字典进行存储,线程非安全
}
3. service中使用cache,my_service.py完整代码
3.1my_service.py中使用cache代码
from flask import Flask
from utils.cache_helper import cache
class MyService:
@staticmethod
def set_my_cache():
# 写入缓存,过期时间为60秒
cache.set('my_cache', "你好!cache", timeout=60)
@staticmethod
def get_my_cache():
# 读取缓存
my_cache = cache.get('my_cache')
return my_cache
4.app.py完整代码
4.1调用my_service.py(MyService类)中的方法
from flask import Flask
from config.config import cache_config
from services.my_service import MyService
from utils.cache_helper import CacheHelper
app = Flask(__name__)
# 初始化cache,硬编码方式配置缓存
# cache = CacheHelper(app, config={'CACHE_TYPE': 'simple'})
# 初始化cache,读取配置文件方式配置缓存
cache = CacheHelper(app, config=cache_config)
@app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
# 写入缓存
@app.route('/api/SetCache')
def set_cache():
MyService.set_my_cache()
return 'success'
# 读取缓存
@app.route('/api/GetCache')
def get_cache():
my_cache = MyService.get_my_cache()
return my_cache
if __name__ == '__main__':
app.run()
4.2启动flask项目,先请求写入缓存接口,再请求读取缓存接口