Flask-在Flask中跨請求傳遞資料資源
前言
由於專案需要,我想在Flask中跨請求傳遞資料資源,而且請求介面必須是非同步非阻塞的方式,Flask的非同步請求已經在這篇文章中解決。
關於g和session
首先我查閱了Flask中的g和session
from flask import g, session
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()
首先用瀏覽器請求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 1
127.0.0.1 - - [2016-10-24 23:10:30] “GET /asyn/ HTTP/1.1” 200 126 4.003038