大多数Pythonic中止缓存装饰器的方法?

时间:2015-11-18 04:45:38

标签: python flask decorator

让我们说我有一个名为server的Flask应用程序,我有如下的缓存蓝图,利用flask.ext.cache中的装饰器:

from flask import Blueprint, render_template, request, Response
from server import cache

some_blueprint = Blueprint('some_blueprint', __name__)

def make_cache_key(*args, **kwargs):
  return request.url

@some_blueprint.route('/')
@cache.cached(timeout = 3600, key_prefix = make_cache_key)
def foo():
  # do some stuff
  if some stuff succeeds:
    return something
  else:
    return "failed"

现在,假设"做一些事情"是99.9%的时间成功的东西,在这种情况下我希望装饰器缓存结果,但0.01%的时间失败,在这种情况下我希望装饰器不缓存"失败"结果

最恐怖的方式是什么?我被迫放弃了装饰者之美吗?

1 个答案:

答案 0 :(得分:2)

(重写我的评论作为答案)

你可以在foo()函数中抛出一个异常,这样它就不会被缓存(大多数缓存函数都会通过异常,参考你的文档)并在包装函数中捕获它来转换它到"failed"。这个包装函数可能是也可能不是装饰器:

def exception_to_failed(func)
  def wrapper(*args, **kwds):
    try:
      res = func(*args, **kwds)
    except: # better catch only specific exceptions, of course
      return "failed"
    return res
  return wrapper

@some_blueprint.route('/')
@exception_to_failed
@cache.cached(timeout = 3600, key_prefix = make_cache_key)
def foo():
  # do some stuff
  if some stuff succeeds:
    return something
  else:
    raise Exception() # or just rely on "some stuff" raising it