Skip to content

Instantly share code, notes, and snippets.

@wilhelm-murdoch
Last active December 15, 2015 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilhelm-murdoch/5331087 to your computer and use it in GitHub Desktop.
Save wilhelm-murdoch/5331087 to your computer and use it in GitHub Desktop.
A decorator used to cache a method's output in redis.
# -*- coding: utf-8 -*-
from functools import wraps
import redis
from flask import Flask, request
from datetime import datetime
app = Flask(__name__)
# -*- coding: utf-8 -*-
from functools import wraps
import redis
from flask import Flask, request
from datetime import datetime
app = Flask(__name__)
HOST = "localhost"
PORT = 6379
r = redis.Redis(host=HOST, port=PORT)
try:
import simplejson as json
except ImportError:
import json
HOST = "localhost"
PORT = 6379
r = redis.Redis(host=HOST, port=PORT)
def redoize(name, ttl, connection):
assert isinstance(name, str)
assert isinstance(ttl, (int, datetime))
assert isinstance(connection, (redis.Redis, redis.StrictRedis))
def decorated(f):
@wraps(f)
def wrapped(*args, **kwargs):
response = connection.get(name)
if not response:
response = f(*args, **kwargs)
connection.set(name, response.data)
if isinstance(ttl, datetime):
connection.pexpireat(name, ttl)
else:
connection.pexpire(name, ttl * (1000 * 60))
return response
return respond_with_json(json.loads(response))
return wrapped
return decorated
@app.route('/')
@redoize(name='test', ttl=1, connection = r)
def hello():
return {'meta': {'api_version': 3}, 'response': {'members': [1, 2, 3, 4, 5]}}
if __name__ == "__main__":
app.run(debug=True)
@app.route('/')
@redoize(name='test', ttl=1, connection = r)
def hello():
return "{'meta': {'api_version': 3}, 'response': {'members': [1, 2, 3, 4, 5]}}"
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment