Flaskful - 在不同请求之间传递数据

Flask 本身不提供缓存,但是它的基础库之一Werkzeug有一些非常基本的缓存支持。

代码:

from flask import Flask, request, g, current_app ,session

from flask_restful import Resource, Api,reqparse

import requests
import json

# gevent
from gevent import monkey, sleep
from gevent.pywsgi import WSGIServer
monkey.patch_all()
# gevent end

import time

# Cache
from werkzeug.contrib.cache import SimpleCache
cache = SimpleCache()
# Cache End



# 请求A: post,并且产生一个变量 key
# 请求B: 需要用到请求A的变量key
# Flask的底层——Werkzeug——是有缓存支持的


    
app = Flask(__name__)

api = Api(app)


app.config.update(DEBUG=True)


# 示例1: 定义两个路由,通过cache传递数据.
@app.route('/asyn/', methods=['GET'])
def test_asyn_one():
    print("asyn has a request!")
    cache.clear()
    timeout = 30
    while (not cache.has('a')) and timeout >0:
        sleep(1)
        timeout = timeout - 1
        print('timeout:', timeout)
    print("a", cache.get('a'))
    return 'hello asyn'
 
 
@app.route('/test/', methods=['GET'])
def test():
    cache.set('a', '1')
    return 'hello test'


# 示例2: 定义flask_restful服务
# 两个服务都是Post方法,请求地址分别是 http://locahost:5000/ttest/1 和 http://locahost:5000/ttest/2  
# 用户访问 /ttest/1 时产生的数据, 通过cache传递给了用户第二次访问 /ttest/2 时使用. 
class TTest(Resource):

    def post(self,todo_id):

            if todo_id is '1':
                cache.clear()
                cache.set('a','aaaaaaaaaa')
                return 1

            elif todo_id is '2':
                x = cache.get('a')
                return x



api.add_resource(TTest, '/ttest/<string:todo_id>')


if __name__ == "__main__":
    # app.run()
    http_server = WSGIServer(('', 5000), app)
    http_server.serve_forever()

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值