tornado-redis
tornado-redis copied to clipboard
wrap redis commands with @return_future decorator
In tornado.concurrent
there is nice decorator return_future
, which allows to return Future
if callback argument is None. With this decorator it is possible to use modern api: yield f(a, b)
and yield gen.Task(f, a, b)
for backward compatibility.
I am not sure about pipelining but for simple commands works perfectly fine:
@return_future
def delete(self, *keys, **kwargs):
self.execute_command('DEL', *keys, callback=kwargs.get('callback'))
@return_future
def set(self, key, value, expire=None, pexpire=None,
only_if_not_exists=False, only_if_exists=False, callback=None):
args = []
if expire is not None:
args.extend(("EX", expire))
if pexpire is not None:
args.extend(("PX", pexpire))
if only_if_not_exists and only_if_exists:
raise ValueError("only_if_not_exists and only_if_exists "
"cannot be true simultaneously")
if only_if_not_exists:
args.append("NX")
if only_if_exists:
args.append("XX")
@return_future
def get(self, key, callback=None):
self.execute_command('GET', key, callback=callback)
and here simple test:
@async_test
engine
def test_get_set_coroutine(self):
res = yield self.client.set('foo', 'bar')
self.assertEqual(res, True)
res = yield self.client.get('foo')
self.assertEqual(res, 'bar')
res = yield self.client.delete('foo')
self.assertTrue(res)
self.stop()
What do you think about decorating all commands with return_future
?
Great! I'll definitely try it.
Thanks a lot!
for i in dir(tornadoredis.Client): if not i.startswith("") and i not in ( "connect", "encode", "listen", "auth", "process_data", "format_reply", ) and not i.startswith("on") and not i.endswith("_command"): attr = getattr(tornadoredis.Client,i) if inspect.isfunction(attr): setattr(tornadoredis.Client,i,return_future(attr))