开发者

Elegant way to cache asynchronous query in Python?

开发者 https://www.devze.com 2023-01-28 20:09 出处:网络
I\'m using开发者_开发百科 Tornado web server and want to take advantage of static caching for an asynchronous query result. Python makes it easy to wrap a function with a cache of some sort, for examp

I'm using开发者_开发百科 Tornado web server and want to take advantage of static caching for an asynchronous query result. Python makes it easy to wrap a function with a cache of some sort, for example using a decorator:

@cache.wrap(ttl=60)
def get_data(arg):
    return do_query(arg)

However, it quickly gets complex using continuation passing:

def wrap_static_result(key, result, callback, ttl):
    cache.set(key, result, ttl)
    callback(result)

def get_data(arg, callback):
    cached = cache.get(arg)
    if cached:
        callback(cached)
    else:
        callback2 = lambda result: wrap_static_result(arg, result, callback, ttl=60)
        do_async_query(arg, callback2)

The most elegant solution I can think of requires making assumptions about call signatures, which isn't always practical. Can anyone think of a nicer way?


Use Deferreds. (The lack of such an abstraction is one of the reasons that Tornado is dramatically inferior to Twisted. You may want to check out Cyclone while you're at it.)

0

精彩评论

暂无评论...
验证码 换一张
取 消