小资料工程师乐园

python: flask的动态cache

2020-06-29  本文已影响0人  luffynoonepiece

cache.set()以及cache.get()的使用

flask的cache功能十分强大,所谓的动态cache,可以将api的回传结果通过设定不同的key分别加入到缓存中,设定timeout或是执行时间,以优化api效能。

话不多说,以下是本机环境下运行的sample code

from flask import Flask,request,render_template,jsonify,Response,render_template_string
from flask_restful import Resource, Api
import datetime
import time
from flask import Blueprint
from flask_caching import Cache
import json

#pip install -i https://pypi.tuna.tsinghua.edu.cn/simple flask_caching
"""
主要是cache.set()和cache.get()的使用,以及设定timeout。
cache.set()可以根据传入的key不同,将多个结果加入缓存。
"""

config = {
    "DEBUG": True,          # some Flask specific configs
    "CACHE_TYPE": "simple", # Flask-Caching related configs
    "CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__)
app.config.from_mapping(config)
#创建cache对象
cache = Cache(app)

@app.route('/')
def get():
    a = {"Python":"Hello World!"}
    #使用flask的jsonify类,使得Content-Type: application/json
    cache_name = "hello"
    cache.set("{}".format(cache_name),a,timeout = 60)
    return '/html/{}'.format(cache_name)

@app.route('/html/<string:foo>')
def html(foo = None):
    if foo is not None:
        bar = cache.get(foo)
        #如果得到的bar类型为response对象,则使用它的data属性获得二进制内容(需进一步使用decode()方法解码)
    else:
        bar = 'error'
    return render_template_string(
        "<html><body>{{bar}}<body/><html/>",bar=bar
    )
    
    #设置返回类型Content-Type: text/html的方法
    """
    return Response(render_template_string(
        "<html><body>{{bar}}<body/><html/>",bar=bar
    ),mimetype='text/html')
    """
    #application/json
    #text/html

if __name__ == '__main__':
    #debug模式默认开启(True),保存修改会被自动更新并运行。
    #默认路径为127.0.0.1:5000
    app.run()
    #设定host为0.0.0.0则本机ip地址为api路径,且端口号设定为5000.
    #app.run('0.0.0.0', 5000, debug = True)
蟹蟹
上一篇下一篇

猜你喜欢

热点阅读