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

相关推荐

  1. Flask模块实践

    2024-07-10 11:54:03       25 阅读
  2. Vue 模块使用 Vuex

    2024-07-10 11:54:03       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 11:54:03       99 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 11:54:03       107 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 11:54:03       90 阅读
  4. Python语言-面向对象

    2024-07-10 11:54:03       98 阅读

热门阅读

  1. docker run/build Dockerfile 修改及完善

    2024-07-10 11:54:03       26 阅读
  2. 基于Gunicorn+Flask+Docker模型高并发部署

    2024-07-10 11:54:03       30 阅读
  3. SQL FOREIGN KEY

    2024-07-10 11:54:03       24 阅读
  4. 安全保障措施

    2024-07-10 11:54:03       25 阅读
  5. Android IdleHandler源码分析

    2024-07-10 11:54:03       29 阅读
  6. docker-1

    docker-1

    2024-07-10 11:54:03      29 阅读
  7. Git批量删除本地h和远程分支说明

    2024-07-10 11:54:03       28 阅读