2016-11-21 114 views
0

我正在研究與redis交互的瓶子應用程序。這個應用程序部署在heroku上,並添加了一個redis。redis獲取函數返回無

當我使用交互進行一些測試時,我無法獲取剛剛設置的鍵值對。相反,我總是將None作爲返回類型。這裏是例子:

import Flask 
    import redis 


    app = Flask(__name__) 
    redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379') 
    redis = redis.from_url(redis_url) 

    @app.route('/test') 
    def test(): 
     redis.set("test", "{test1: test}") 
     print redis.get("test") # print None here 
     return "what the freak" 


    if __name__ == "__main__": 
     app.run(host='0.0.0.0') 

如上所示,測試路由將打印None,表示該值未設置。我很困惑。當我在本地瀏覽器上測試服務器時,它起作用,當我嘗試使用heroku python shell與redis進行交互時,它也可以工作。

與蟒蛇外殼測試:

heroku run python 
from server import redis 
redis.set('test', 'i am here') # return True 
redis.get('test') # return i am here 

我現在很困惑。我應該如何正確使用Flask與redis進行交互?

回答

0

我對此做了更多的實驗。似乎有一個與延遲有關的問題。下面的修改將使它的工作:

@app.route('/test') 
    def test(): 
     redis.set("test", "{test1: test}") 
     time.sleep(5) # add the delay needed to the let the set finish 
     print redis.get("test") # print "{test1: test}" here 
     return "now it works" 

我讀了關於redis的文檔,redis似乎是單線程。所以我不確定爲什麼它會在set函數完成之前執行get函數調用。有更多經驗的人請發表解釋。

1

Redis-py默認構建一個ConnectionPool客戶端,這可能是from_url幫助函數正在做的事情。儘管Redis本身是單線程的,但連接池中的命令沒有保證的執行順序。對於單個客戶端,直接構建一個redis.StrictRedis客戶端,或者通過參數connection_pool=none。這對於簡單的命令來說比較好,數量少,因爲連接管理開銷較小。您也可以在連接池的上下文中使用管道來序列化批處理操作。

https://redis-py.readthedocs.io/en/latest/#redis.ConnectionPool

https://redis-py.readthedocs.io/en/latest/#redis.Redis.pipeline