1

I am working on my first Flask Restful API and I'm trying to cache it for a week so that it only sends out a single request to update on Sundays. I am planning to upload it to Heroku on a Sunday so that the timeout (604800) I've set is synced to Sunday. I am able to create the page that displays JSON just fine but I am looking for some advice with the caching bit as I have a feeling that I am not doing it correctly and I'm not sure how to check it locally to see if it even works before uploading it to Heroku.

from flask import Flask
from flask_caching import Cache
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

cache = Cache(app, config={'CACHE_TYPE': 'simple'})

class Products(Resource):
    @cache.cached(timeout=604800) # cache set to 1 week in seconds
    def get(self):
        product_list = []
        item_count = len(product)
        for x in range(item_count):
            product_list.append({'title':product[x].title, 'url':product[x].url,'image':product[x].images.medium})
        return {'product_list':product_list}


api.add_resource(Products, '/')

1 Answer 1

1

Looks good, you can easily check if the caching is working by putting a time.sleep(60) into your route

if the caching doesnt work, it will wait 1 minute before sending a response every time - if everything is set up correctly, it will only do so once a week (because when caching is active, the line "sleep" will no longer be executed)

you can check this locally with Postman, or by simply visiting the url in your browser

-> remember to remove this obviously before going live!

here's a good video about it https://www.youtube.com/watch?v=iO0sL6Vyfps

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

Comments

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.