Skip to content

Instantly share code, notes, and snippets.

@vterron
Created February 22, 2015 17:54
Show Gist options
  • Save vterron/70a719a9de8536a30190 to your computer and use it in GitHub Desktop.
Save vterron/70a719a9de8536a30190 to your computer and use it in GitHub Desktop.
A Python multiple-server memcached decorator
#! /usr/bin/env python
# Author: Victor Terron (c) 2015
# Email: `echo vt2rron1iaa32s | tr 132 @.e`
# License: GNU GPLv3
""" A memcached function decorator. """
from __future__ import division
from __future__ import print_function
import functools
import memcache
def optional_arguments(func):
""" A decorator to make another decorator take optional arguments.
Based on: https://stackoverflow.com/a/20966822/184363 """
def wrapped_decorator(*args, **kwargs):
if len(args) == 1 and callable(args[0]):
return func(args[0])
else:
def real_decorator(decoratee):
return func(decoratee, *args, **kwargs)
return real_decorator
return wrapped_decorator
@optional_arguments
def memcached(func, servers, port=11211, time=1200, debug=1):
""" A decorator to cache function results using memcached.
Based on: https://gist.github.com/abahgat/1395810 """
hosts = ['{0}:{1}'.format(s, port) for s in servers]
mcache = memcache.Client(hosts, debug=debug)
@functools.wraps(func)
def memf(*args, **kwargs):
key = '{0}{1}{2}'.format(func.__name__, args, kwargs)
value = mcache.get(key)
if value is None:
value = func(*args, **kwargs)
mcache.set(key, value, time=time)
return value
return memf
servers = ['feynman', 'localhost']
@memcached(servers=servers)
def fibonacci(n):
""" Return the n-th Fibonacci number. """
if n in [0, 1]:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == "__main__":
print(fibonacci(299))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment