前言
由于项目需要,我想在Flask中跨请求传递数据资源,而且请求接口必须是异步非阻塞的方式,Flask的异步请求已经在这篇文章中解决。
关于g和session
首先我查阅了Flask中的g和session
from flask import g, session
- 1
g——处理请求时用作临时存储的对象,每次请求会重设这个变量;
session——用户会话,用于存储请求之间需要「记住」的值的词典;
简单来说,每一个请求的g变量都是独立的g变量,不同请求之间的g的数据是不互通的。
session是可以「记住」前后请求,但是他是使用了浏览器的Cookie,是保存在客户端的一种方法。我这里需要的是保存在服务器的session,所以Flask的session也帮不上忙。
解决办法
一种解决办法是使用外部的内存管理,比如Redis;如果项目足够大,数据资源比较多,使用外部内存管理是正确的方法。可是我现在只是想跨请求传递一点点数据,不想使用Redis。这个时候找到了这篇资料。
Flask 本身不提供缓存,但是它的基础库之一Werkzeug有一些非常基本的缓存支持。
Flask的底层——Werkzeug——是有缓存支持的,于是我参考了上面链接提供的例子,简单实现了跨请求传递数据。不用再安装Redis了。
代码清单
# coding=utf-8
# Python Version: 3.5.1
# Flask
from flask import Flask, request, g, current_app
# 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
app = Flask(__name__)
app.config.update(DEBUG=True)
@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'
if __name__ == "__main__":
# app.run()
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
首先用浏览器请求http://127.0.0.1:5000/asyn/
接口,这个时候会打印
asyn has a request!
之后开始倒计时。再请求http://127.0.0.1:5000/test/
最后上面的asyn函数在缓存中找到了key,跳出while循环。
完整打印如下:
asyn has a request!
timeout: 29
timeout: 28
timeout: 27
127.0.0.1 - - [2016-10-24 23:10:30] “GET /test/ HTTP/1.1” 200 126 0.000000
timeout: 26
a 1127.0.0.1 - - [2016-10-24 23:10:30] “GET /asyn/ HTTP/1.1” 200 126 4.003038
出处:https://blog.csdn.net/yannanxiu/article/details/52916892