Python:Flask缓存无法在特定时间范围内工作

时间:2018-03-13 13:27:53

标签: python caching flask

我创建的Flask应用程序只能在时间范围之外才能工作但如果它在时间范围内(if路径)则返回错误

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cache import Cache
from datetime import datetime, time
app.config['CACHE_TYPE'] = 'simple'
app.cache = Cache(app)

    @app.route('/thtop', methods=['GET'])
    @app.cache.cached(timeout=60)
    def thtop():
        now = datetime.now()
        now_time = now.time()
        if now_time >= time(3,30) and now_time <= time(16,30):
            rv = app.cache.get('last_response')
        else:
           rv = 'abcc'
            app.cache.set('last_response', rv, timeout=3600)
        return rv

如果if路径中的时间,则无法显示字符串abcc,但显示为Internal Server Error

在WSGI错误日志中,它还显示了Exception on /thtop [GET]#012Traceback (most recent call last):#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app#012 response = self.full_dispatch_request()#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1361, in full_dispatch_request#012 response = self.make_response(rv)#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1439, in make_response#012 raise ValueError('View function did not return a response')#012ValueError: View function did not return a response

我在缓存时出了什么问题?

更新

使用flask_caching模块,但仍然是相同的失败

from flask.ext.sqlalchemy import SQLAlchemy
from flask_caching import Cache
from datetime import datetime, time

cache = Cache(app, config={'CACHE_TYPE': 'simple'})

@app.route('/thtop', methods=['GET'])
@cache.cached(timeout=60)
def thtop():
    now = datetime.now()
    now_time = now.time()
    if now_time >= time(3,30) and now_time <= time(14,30):
        rv = cache.get('last_response')
    else:
        rv = 'abcc'
        cache.set('last_response', rv, timeout=3600)

    return rv

我在控制台中运行时在不同模块中观察到的差异,从def thtop()开始,app.cache.get('last_response')不返回任何内容。但是,cache.get('last_response')会返回abcc

问题是在网络应用中运行时,会导致错误,如上所示。

2 个答案:

答案 0 :(得分:2)

每当now_time >= time(3,30) and now_time <= time(14,30)Truerv = cache.get('last_response')None时,您才会收到错误消息。当发生这种情况时,您会尝试从导致None的视图中返回ValueError

您需要添加一些额外的逻辑来检查缓存是否实际返回数据:

from flask import Flask                                                         
from flask_caching import Cache                                                 
from datetime import datetime, time                                             

app = Flask(__name__)                                                           

app.config['SECRET_KEY'] = 'secret!'                                            
app.config['DEBUG'] = True                                                      

cache = Cache(app, config={'CACHE_TYPE': 'simple'})                             


@app.route('/thtop', methods=['GET'])                                           
@cache.cached(timeout=60)                                                       
def thtop():                                                                    

    now = datetime.now()                                                        
    now_time = now.time()                                                       

    rv = None                                                                   

    if now_time >= time(3, 30) and now_time <= time(14, 30):                    
        rv = cache.get('last_response')                                         

    if not rv:                                                                  
        rv = 'abcc'                                                             
        cache.set('last_response', rv, timeout=3600)                            

    return rv                                                                   


if __name__ == '__main__':                                                      
    app.run()

有了这个逻辑,你的路线总会返回一些东西,所以你不会得到ValueError

答案 1 :(得分:0)

这句话似乎是Trueif now_time >= time(3,30) and now_time <= time(16,30)

这就是为什么你试图从last_response得到rv = app.cache.get('last_response')值,我认为这等于None

引发内部服务器错误,因为您返回的NoneType对象无效。您应该返回function()'a string'

尝试通过将app.cache.get('last_response')更改为app.cache.get('last_response', 'FIXED')

来修复此错误