3

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.

7
  • 1
    Can you please explain in detail what you are objective is. Not sure why you are using flask.set and get. what do you want to do. Probably you are not using the cache in the right way . Commented Mar 13, 2018 at 17:36
  • You don't need to set cache. Flask cache will remember your last response(cache it) for the given time period which you have set as 60 seconds. Not a very useful cache probably if it gets cleared every minute but it depends Commented Mar 13, 2018 at 18:04
  • @Shamik, the function shall get data from a link if it is out of the time range. If within the time range, it will use cache. Also, the @app.cache.cached(timeout=60) is to allow only one query in 60s so that I will not block by the link Commented Mar 14, 2018 at 2:33
  • Hmm, I got what you are trying. Just a guess. Could it be that the timeout in the method clears all the things set within its context ? can you remove that and check if the error is still coming. Commented Mar 14, 2018 at 7:06
  • I have try numerous thing by removing each line. I found out the only thing I found is during the if path, it will fail. Timeout? Which of the timeout you refer to?@app.cache.cached(timeout=60) definitely not affected the result as without it, it will still fail Commented Mar 14, 2018 at 7:12

2 Answers 2

3
+50

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Matt, is rv= None is important? I skip it and it seems to work in this conditon
Yes you should declare rv here, because it the now_time condition is false then rv will never be declared and the "if not rv" condition will cause an UnboundLocalError
0

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

4 Comments

Same error with your answer. You can change the time to any to test, just it still return the error I shown if the statement if is True. Else, it will print the string
So, the only problem is during the cache.get. I am not sure if it is working as I do not find any good example. I am using from flask.ext.cache import Cache
@lotteryman maybe this will let you get an answer: github.com/thadeusb/flask-cache/issues/156
from flask_caching import Cache does not have the effect. Still same failures

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.