我创建的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_缓存模块,但仍然失败
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应用程序中运行时,它将导致如上所示的错误。
最佳答案
当now_time >= time(3,30) and now_time <= time(14,30)
是True
并且rv = 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
。