I want to cache the results of a flask function which is called by an event on my Website:

This is the function on flask:

@app.route('/request_hourly_prediction')
def request_hourly_prediction():
    number = request.args.get('s_num')

    # do some stuff...
    # return jsonify(results)

And this is how is called by the website:

function func3(x) {
    $.getJSON(ROOT + '/request_hourly_prediction?s_num=' + x, null, function(data1) {
    // do stuff...
}

As you can see, I pass an argument to the function using request.args.get('s_num') I want to cache the results of the function based on the argument I pass: I tried with @lru_cache(maxsize=32) but it cache the function result regardless of the argument given.

I also saw some decorator functions that holds the results based on the arguments passed to a python function but the problem in this case is that I'm not actually passing any arguments inside the function call but I'm getting them from inside the function using request.args.get('s_num').

1 Answers

0
user11300 On Best Solutions

Something like this:

@app.route('/request_hourly_prediction')
def request_hourly_prediction():
    number = request.args.get('s_num')
    return jsonify(compute(number))

@lru_cache(maxsize=32)
def compute(number):
  # do computation
  return results

You could probably also put the jsonify inside compute if you wanted.