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

标签 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”,第 1687 行,在 wsgi_app#012 response = self.full_dispatch_request()#012 文件“/usr/local/lib/python2.7/dist-packages/flask/app.py”,第 1361 行,在full_dispatch_request#012 response = self.make_response(rv)#012 文件“/usr/local/lib/python2.7/dist-packages/flask/app.py”,第 1439 行,在 make_response#012 raise ValueError('View function没有返回响应')#012ValueError: View 函数没有返回响应

缓存时出了什么问题?

更新

使用 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

问题是在 web app 中运行时,会出现如上所示的错误。

最佳答案

每当 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 .

关于Python:Flask 缓存无法在特定时间范围内工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49257427/

相关文章:

c# - .NET 缓存滑动过期如何工作?

flask - TypeError:__init __()获得了意外的关键字参数'password'

python - 模板文件更改时重新加载 Flask 应用程序

postgresql - Fedora:应用程序容器无法建立与数据库容器的连接

python - 在 Python 中接收电子邮件

Python/Tensorflow - 我训练了卷积神经网络,如何测试它?

python - Python 中的步骤信息

python - Python 字典可以作为 Neo4j 文字映射传递吗?

c# - 在 ASP.NET 中使用静态字段来缓存大对象是不好的做法吗?

spring - 在 Spring MVC Rest 服务中缓存 HTTP 响应