Skip to content

Instantly share code, notes, and snippets.

@jhorman
Last active August 29, 2015 14:22
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 jhorman/02d2c2dd5081ad2b6e0e to your computer and use it in GitHub Desktop.
Save jhorman/02d2c2dd5081ad2b6e0e to your computer and use it in GitHub Desktop.
Promises for redis-py
from __future__ import absolute_import
import functools
from aplus import Promise
class PPromise(Promise):
def __init__(self, pipeline):
Promise.__init__(self)
self.pipeline = pipeline
def get(self, timeout=None):
if self.isPending:
self.pipeline.execute()
return Promise.get(self, timeout)
class PromisePipeline(object):
def __init__(self, redis):
super(PromisePipeline, self).__init__()
self.pipeline = redis.pipeline()
self.__pending = []
def __wrap(self, method, *args, **kwargs):
f = getattr(self.pipeline, method)
f(*args, **kwargs)
p = PPromise(self)
self.__pending.append(p)
return p
def execute(self):
results = self.pipeline.execute()
for index, result in enumerate(results):
self.__pending[index].fulfill(result)
self.__pending = []
return results
def __getattr__(self, method):
return functools.partial(self.__wrap, method)
@jhorman
Copy link
Author

jhorman commented Jun 9, 2015

p = PromisePipeline(redis)
p.set("a", "1")
value = p.get("a").get()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment