|
| 1 | +import redis |
| 2 | +from flask import Flask |
| 3 | + |
| 4 | +# redis |
| 5 | +redis_cache = redis.Redis(host='localhost', port=6379, db=0, password="") |
| 6 | + |
| 7 | +# flask app |
| 8 | +app = Flask(__name__) |
| 9 | + |
| 10 | +# set with expire |
| 11 | +@app.route('/set/<string:key>/<string:value>/<int:expired>') |
| 12 | +def set_with_expire(key, value, expired): |
| 13 | + if redis_cache.exists(key): |
| 14 | + pass |
| 15 | + else: |
| 16 | + redis_cache.set(key, value, ex=expired) |
| 17 | + return "OK" |
| 18 | + |
| 19 | +# set |
| 20 | +@app.route('/set/<string:key>/<string:value>') |
| 21 | +def set(key, value): |
| 22 | + if redis_cache.exists(key): |
| 23 | + pass |
| 24 | + else: |
| 25 | + redis_cache.set(key, value) |
| 26 | + return "OK" |
| 27 | + |
| 28 | +# get |
| 29 | +@app.route('/get/<string:key>') |
| 30 | +def get(key): |
| 31 | + if redis_cache.exists(key): |
| 32 | + return redis_cache.get(key) |
| 33 | + else: |
| 34 | + return f"{key} is not exists" |
| 35 | + |
| 36 | +# expire |
| 37 | +@app.route('/expire/<string:key>/<int:expired>') |
| 38 | +def expire(key, expired): |
| 39 | + if redis_cache.exists(key): |
| 40 | + # ref: https://realpython.com/python-redis/ |
| 41 | + # ref: https://redis-py.readthedocs.io/en/stable/_modules/redis/client.html#Redis.expire |
| 42 | + # redis_cache.expire(key, timedelta(seconds=expired)) |
| 43 | + print(f"Set expire {key} after {expired} seconds!") |
| 44 | + redis_cache.expire(key, expired) |
| 45 | + return "Done, expire set!" |
| 46 | + else: |
| 47 | + return f"{key} is not exists, please set this at the first" |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + app.run("127.0.0.1", port="5000", debug=True) |
0 commit comments