thadeusb / flask-cache

Cache extension for Flask
http://packages.python.org/Flask-Cache/
Other
697 stars 185 forks source link

I built a simple instagram client api that takes a user id and queries posts by the user. How do I cache the results per id? #203

Open adrianocr opened 4 years ago

adrianocr commented 4 years ago

Here's the flask route/functionality:

@app.route('/')
# @cache.cached(timeout=300)
@cross_origin('*')
def index():
    user_id = request.args.get('user_id')
    image_count = request.args.get('image_count', 20, int)
    web_api = InstaClient(auto_patch=True, drop_incompat_keys=False)
    user_feed_info = web_api.user_feed(user_id, count=image_count)
    posts = []
    for post in user_feed_info:
        post = post['node']
        posts.append(
            {
                'id': post['id'],
                'link': post['link'],
                'display_url': post['thumbnail_resources'][2]['src'],
                'display_url_2x': post['thumbnail_resources'][4]['src'],
            }
        )

    return jsonify(posts)

Notice the commented out @cache.cached(timeout=300) on line 2. I tried that and it works but then the issue is that it caches it for the first user_id that was provided and returns wrong results for any subsequent user_id until the cache expires and then the issue starts all over again with the first user_id provided after the cache expires.

I want to do this where each user_id gets its own cache of results. Any tips on how?

The instagram api is notoriously strict on rate limits (seemingly random too) so if I don't start caching results to reduce queries, my client will probably get banned soon.