Tuesday, December 3, 2019

How to Caching Post Requests to redis Server in Python Flask, Redis Using Decorators

from flask import Flask, jsonify, request
from functools import wraps
import redis
import json

r = redis.Redis('__ip_address_redis_server__')
cache_time = 10

def xcaching(f):
    @wraps(f)
    def decor(*args, **kwargs):
        check = request.get_json()
        get_from_redis = r.get(str(check))

        if get_from_redis:
            data = get_from_redis.decode('utf-8')
            ret = json.loads(data)
            r.expire(str(check), cache_time)
            return jsonify(ret)

        ret = f(*args, **kwargs)

        cache_to_redis = ret.get_data()
        r.set(str(check), cache_to_redis ex=cache_time)

        return ret
    return decor


@app.route('/search', methods=['POST'])
@xcaching
def main():
req = request.get_json()
ret = call_api_function(req)
return jsonify(ret)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

ALCATEL 6900

write memory copy running certified reload from working no rollback-timeout