lotteryman
lotteryman

Reputation: 399

Python: Flask cache unable to work in specific time range

the Flask app I create only able to work if it outside the time range but return error if it is within the time range (the if path)

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 the time in the if path, it unable to show the string abcc but shown Internal Server Error.

In WSGI error log, it also shown 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

What is wrong when I am caching?

UPDATE

Use flask_caching module but still same failures

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

The difference I observed in both different module when I run in console, starting from def thtop(), app.cache.get('last_response') return nothing. However, cache.get('last_response') return abcc.

The problem is when run in web app, it will cause error as shown above.

Upvotes: 3

Views: 1752

Answers (2)

Matt Healy
Matt Healy

Reputation: 18531

You're getting the error whenever now_time >= time(3,30) and now_time <= time(14,30) is True and rv = cache.get('last_response') is None. When that happens, you're trying to return None from the view which causes the ValueError.

You need to add some additional logic to check that the cache actually returns data:

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()

with this logic your route will always return something so you won't get the ValueError.

Upvotes: 3

py_dude
py_dude

Reputation: 832

Seems like this statement is True: if now_time >= time(3,30) and now_time <= time(16,30)

That is why you are trying to get the last_response value from rv = app.cache.get('last_response') which is equal to None I think.

The Internal Server Error is thrown because you return a NoneType object that is not valid. You should return a function() or 'a string' instead.

Try fixing this Error by changing app.cache.get('last_response') to app.cache.get('last_response', 'FIXED')

Upvotes: 0

Related Questions