flask模块化、封装使用缓存cache(flask_caching)

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项目,先请求写入缓存接口,再请求读取缓存接口

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值