Using Flask with ExpiringDict

Installation

  • python library
    $ pip install expiringdict
    

Sample Code

from flask import Flask
from expiringdict import ExpiringDict

app = Flask(__name__)
cache = ExpiringDict(max_len=100, max_age_seconds=10)

def expensive_function(s_id):
    return computing_result

@app.route('/sample/<int:s_id>', methods=['GET')
def sample(s_id):
    cache[s_id] = cache.get(request_id)  # to reset expiry time 
    if cache[s_id]:  # if the id of cache has value
        result = cache.get(request_id)  # get value in cache
    else:  # if the id of cache has no value or expired
        result = expensive_function(s_id)  # get value by expensive function
        cache[s_id] = result  # set the id of cache's value
    return result

results matching ""

    No results matching ""