Created
June 19, 2015 09:52
-
-
Save pistatium/ba43221b4e9764ac7820 to your computer and use it in GitHub Desktop.
関数をRedisでキャッシュするためのデコレータ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from __future__ import absolute_import, division, print_function | |
import pickle | |
import functools | |
import redis | |
def cache(expire_time=1200): | |
""" | |
@param expire_time キャッシュ時間 sec | |
""" | |
def decorator(function): | |
@functools.wraps(function) | |
def wrapper(*args, **kwargs): | |
key = 'c:%s:%s:%s' % (function.__name__, str(args), str(kwargs)) | |
slave = redis.Redis(host=REDIS_SLAVES_HOST) | |
saved_value = slave.get(key) | |
if saved_value: | |
return pickle.loads(saved_value) | |
else: | |
value = function(*args, **kwargs) | |
if value is not None: | |
master = redis.Redis(host=REDIS_MASTER_HOST) | |
master.setex(key, pickle.dumps(value), expire_time) | |
return value | |
return wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment