Skip to content

Instantly share code, notes, and snippets.

@shihongzhi
Created October 21, 2012 05:16
Show Gist options
  • Save shihongzhi/3925952 to your computer and use it in GitHub Desktop.
Save shihongzhi/3925952 to your computer and use it in GitHub Desktop.
洪教授python在web 2.0 网站中的应用演讲中 gen_key_factory函数的自己实现版本
import doctest
import inspect
def gen_key_factory(key_pattern, arg_names, defaults):
"""
产生gen_key 函数的工厂
洪教授python在web 2.0 网站中的应用演讲中 gen_key_factory函数的自己实现版本
"""
def gen_key(*a, **kw):
values = list(a)
alen = len(arg_names)
vlen = len(values)
if vlen < alen:
values.extend(defaults[vlen-alen:])
d = dict(zip(arg_names, values))
for x in kw:
d[x] = kw[x]
return key_pattern.format(**d)
return gen_key
def cache(key_pattern, expire=0):
def deco(f):
arg_names, varargs, varkw, defaults = inspect.getargspec(f)
if varargs or varkw:
raise Exception("not support varargs")
gen_key = gen_key_factory(key_pattern, arg_names, defaults)
def _(*a, **kw):
key = gen_key(*a, **kw)
print key
return f(*a, **kw)
return _
return deco
@cache('review:{id}:{id1}:{id2}')
def get_review(id, id1=0, id2=10):
"""Return the factorial of n, an exact integer >= 0.
>>> get_review(10)
review:10:0:10
>>> get_review(10, 1)
review:10:1:10
>>> get_review(10, 12, 13)
review:10:12:13
>>> get_review(1, id2=14)
review:1:0:14
"""
pass
if __name__ == '__main__':
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment