The use of Flask-Cache

When a resource needs to be obtained from the server, and the resource is relatively large, the server may process it slowly, and this function is a popular function, and users may need to access it frequently. At this point, the server can consider caching technology. The cache is the buffer (called Cache) for data exchange. When a certain hardware wants to read data, it will first look for the required data from the cache. If it is found, it will be executed directly. If it cannot be found, it will be found in memory. Since the cache runs much faster than the memory, the purpose of the cache is to help the hardware run faster. Next, I will record how to cache a Flask request, and record the Flask cache extension library Flask-Cache:

Install

pip install flask-cache
  • 1

initialization

When we have the Flask-Cachemodule installed, we also need to instantiate it and configure it accordingly:

from flask import Flask
from flask_cache import Cache

app = Flask(__name__)
cache = Cache(app,config={
    "CACHE_TYPE":"simple"
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

You can also init_app()set up your instance later using the method:

app = Flask(__name__)
cache = Cache(config={
    "CACHE_TYPE":"simple"
})
cache.init_app(app)
  • 1
  • 2
  • 3
  • 4
  • 5

Or also this:

app = Flask(__name__)
cache = Cache()
cache.init_app(app,config={
    "CACHE_TYPE":"simple"
})
  • 1
  • 2
  • 3
  • 4
  • 5

cache view function

To cache view functions, you can use a @cache.cached()decorator that uses request.path as cache_key by default:

@app.route("/get_info")
@cache.cached()
def get_info():
    print "no cache"
    return "it is ok!"
  • 1
  • 2
  • 3
  • 4
  • 5

@cache.cached()The decorator can also receive parameters, such as the parameter timeoutsetting the cache expiration time; the parameter unlessreceives a value of type Bool, if set to, Truethe cache mechanism will not be used; the parameter key_prefixreplaces the default cache_key

cache other functions

Use the @cache.cached()decorator to cache the results of other non-view-related functions. When using the @cache.cached()decorator to cache the results of non-view-related functions, it is recommended to pass in a parameter key_prefixto replace the default cache_key, otherwise it will use request.path as the cache_key by default:

@cache.cached(timeout=30,key_prefix="aaa")
def sum_data(a,b):
    return int(a) + int(b)
  • 1
  • 2
  • 3

memoize ()

In the @cache.memoize()decorator, the parameters of the function are also included in the cache_key:

@cache.memoize(timeout=30)
def sum_data(a,b):
    return int(a) + int(b)
  • 1
  • 2
  • 3

It is worth noting that for functions that take no arguments, the @cache.memoize()same @cache.cached()as

清除缓存

以下是一个用于清除应用程序缓存的示例脚本:

from manager import app,cache

with app.app_context():
    cache.clear()
  • 1
  • 2
  • 3
  • 4

配置

Flask-Cache支持多个类型作为缓存后端,不同的缓存后端,配置项也不尽相同,接下来记录一下Flask-Cache支持的缓存后端:

  • null:无缓存。相关配置项如下:
配置 说明
CACHE_ARGS 在缓存类实例化过程中解包和传递的可选列表
CACHE_OPTIONS 可选字典在缓存类实例化期间传递

simple:使用本地python字典进行存储,这不是线程安全的。相关配置项如下:

配置 说明
CACHE_DEFAULT_TIMEOUT 默认过期/超时时间,单位为秒
CACHE_THRESHOLD 缓存的最大条目数
CACHE_ARGS 在缓存类实例化过程中解包和传递的可选列表
CACHE_OPTIONS 可选字典在缓存类实例化期间传递

filesystem:使用文件系统来存储缓存的值。相关配置项如下:

配置 说明
CACHE_DEFAULT_TIMEOUT 默认过期/超时时间,单位为秒
CACHE_DIR 存储缓存的目录
CACHE_THRESHOLD 缓存的最大条目数
CACHE_ARGS 在缓存类实例化过程中解包和传递的可选列表
CACHE_OPTIONS 可选字典在缓存类实例化期间传递

memcached:使用memcached服务器作为缓存后端,支持pylibmcmemcache或Google应用程序引擎memcache库。相关配置项如下:

配置 说明
CACHE_DEFAULT_TIMEOUT 默认过期/超时时间,单位为秒
CACHE_KEY_PREFIX 设置cache_key的前缀
CAHCE_MEMCACHED_SERVERS 服务器地址的列表或元组
CACHE_ARGS 在缓存类实例化过程中解包和传递的可选列表
CACHE_OPTIONS 可选字典在缓存类实例化期间传递

- redis:使用Redis作为缓存后端。相关配置项如下

配置 说明
CACHE_DEFAULT_TIMEOUT 默认过期/超时时间,单位为秒
CACHE_KEY_PREFIX 设置cache_key的前缀
CACHE_REDIS_HOST redis地址
CACHE_REDIS_PORT redis端口
CACHE_REDIS_PASSWORD redis密码
CACHE_REDIS_DB 使用哪个库
CACHE_REDIS_URL 连接到Redis服务器的URL。示例redis://user:password@localhost:6379/2
CACHE_ARGS 在缓存类实例化过程中解包和传递的可选列表
CACHE_OPTIONS 可选字典在缓存类实例化期间传递

举个栗子:

from flask import Flask
from flask_cache improt Cache

app = Flask(__name__)
cache = Cache(app,config={
    "CACHE_TYPE":"redis",
    "CACHE_REDIS_HOST":"192.168.0.158",
    "CACHE_REDIS_PORT":6379,
    "CACHE_REDIS_PASSWORD":"123456",
    "CACHE_REDIS_DB":2
})

@app.route("/get_info")
@cache.cached(timeout=30)
def get_info():
    print "no cache!"
    return "it is ok!"

if __name__ == "__main__":
    app.run()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • saslmemcached:使用memcached服务器作为缓存后端,打算与支持SASL的连接一起使用到memcached服务器。pylibmc是必须的,SASL必须由libmemcached支持。相关配置项如下:
配置 说明
CACHE_DEFAULT_TIMEOUT 默认过期/超时时间,单位为秒
CACHE_KEY_PREFIX 设置cache_key的前缀
CAHCE_MEMCACHED_SERVERS 服务器地址的列表或元组
CACHE_MEMCACHED_USERNAME 使用memcached进行SASL认证的用户名
CACHE_MEMCACHED_PASSWORD 使用memcached进行SASL认证的密码
CACHE_ARGS 在缓存类实例化过程中解包和传递的可选列表
CACHE_OPTIONS 可选字典在缓存类实例化期间传递
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/y472360651/article/details/79847933

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325951422&siteId=291194637