Caching 在Python中缓存异步查询的优雅方式?
我使用的是TornadoWeb服务器,希望利用静态缓存实现异步查询结果。Python使使用某种缓存包装函数变得很容易,例如使用decorator:Caching 在Python中缓存异步查询的优雅方式?,caching,asynchronous,twisted,decorator,tornado,Caching,Asynchronous,Twisted,Decorator,Tornado,我使用的是TornadoWeb服务器,希望利用静态缓存实现异步查询结果。Python使使用某种缓存包装函数变得很容易,例如使用decorator: @cache.wrap(ttl=60) def get_data(arg): return do_query(arg) 但是,使用连续传递很快就会变得复杂: def wrap_static_result(key, result, callback, ttl): cache.set(key, result, ttl) call
@cache.wrap(ttl=60)
def get_data(arg):
return do_query(arg)
但是,使用连续传递很快就会变得复杂:
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)
我能想到的最优雅的解决方案需要对呼叫签名进行假设,这并不总是可行的。有人能想出更好的方法吗?使用。(Tornado明显不如Twisted,原因之一是缺乏这样的抽象概念。你可能想边看边看。)使用。(Tornado明显不如Twisted,原因之一是缺乏这种抽象。你可能想在玩的时候查看一下。)值得一提的是,你在这里称之为“继续传递”的实际上是“回调传递”。延续传递要求语言支持延续,而Python不支持延续(至少不是开箱即用)。延续传递要求语言支持延续,而Python不支持延续(至少不是开箱即用)。