HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonflaskMinor

Caching a function view for a day

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
cachingfunctionviewforday

Problem

I am writing a flask app that I will deploy it on Heroku to test it. There is a page that will generate daily photos and information based on a JSON file. The view is valid for 24 hours beginning from 00:00 to 23:59 of everyday.

I am thinking about using a cache, otherwise the app will consume unnecessary resources.

import ..

TODAY = date.today()

 app = Flask(__name__)
 app.jinja_env.auto_reload = False
 cache = Cache(config={'CACHE_TYPE': 'simple', 'CACHE_ARGS' : TODAY})
#This function reads a json file, filter the daily data to process and render a html template with photos and text .

# 3600 *  24 = 86400
@cache.cached(timeout=86400)
@app.route('/inf')
def inf():
    input_file = open(os.path.join(__location__, 'json/output.json'));    
    j = json.loads(input_file.read().decode("utf-8-sig"))
    etc ..

    return render_template('inf.html', 
                        title = title,
                        config={'environment_args':{'autoescape':False}},
                        zipped =zipped) 

if __name__ == '__main__':
    if TODAY != cache.config['CACHE_ARGS'] :
        with app.app_context():
            cache.clear()                
    port = int(os.environ.get('PORT', 33507))
    app.run(debug = True, host='0.0.0.0', port=port)


I am not sure if this is the best solution to cache the view for a day. That's why I am asking here for more suggestions.

Solution

Why not take advantage of the RESTful architecture of the internet? I suggest you have the code generate a static page and set the expires header on that resource (or set of resources) to the end of that day (considering your audience's time zones, I guess). This might help.

Sorry, if I had experience with heroku or flask I would provide code or more details.

Context

StackExchange Code Review Q#37366, answer score: 2

Revisions (0)

No revisions yet.