更新信息时请求缓存是否自动更新缓存?

2024-06-16 10:46:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python请求一个非常不可靠的API。我一直在考虑使用requests_cache并将expire_after设置为999999999,就像我见过的其他人那样。 唯一的问题是,我不知道当API再次运行时,是否更新了数据。如果请求,缓存将自动更新并删除旧条目。在

我试过看医生,但我在任何地方都看不到。在


Tags: 数据apicache地方条目requests医生after
2条回答

requests_cacheexpire_after时间过去之前,requests_cache不会更新。在这种情况下,你的API将检测不回工作状态。在

我注意到项目已经添加了一个我在过去实现的选项;现在您可以在配置缓存时设置old_data_on_error选项;请参见^{} documentation

old_data_on_error – If True it will return expired cached response if update fails.

如果后端更新失败,它将重用现有的缓存数据,而不是删除这些数据。在

过去,我创建了自己的requests_cache会话设置(加上小补丁),如果后端出现500个错误或超时(使用短超时)来处理有问题的API层,则会在expire_after之外重用缓存值,而不是依赖expire_after

import logging

from datetime import (
    datetime,
    timedelta
)
from requests.exceptions import (
    ConnectionError,
    Timeout,
)
from requests_cache.core import (
    dispatch_hook,
    CachedSession,
)

log = logging.getLogger(__name__)
# Stop logging from complaining if no logging has been configured.
log.addHandler(logging.NullHandler())


class FallbackCachedSession(CachedSession):
    """Cached session that'll reuse expired cache data on timeouts

    This allows survival in case the backend is down, living of stale
    data until it comes back.

    """

    def send(self, request, **kwargs):
        # this *bypasses* CachedSession.send; we want to call the method
        # CachedSession.send() would have delegated to!
        session_send = super(CachedSession, self).send
        if (self._is_cache_disabled or
                request.method not in self._cache_allowable_methods):
            response = session_send(request, **kwargs)
            response.from_cache = False
            return response

        cache_key = self.cache.create_key(request)

        def send_request_and_cache_response(stale=None):
            try:
                response = session_send(request, **kwargs)
            except (Timeout, ConnectionError):
                if stale is None:
                    raise
                log.warning('No response received, reusing stale response for '
                            '%s', request.url)
                return stale

            if stale is not None and response.status_code == 500:
                log.warning('Response gave 500 error, reusing stale response '
                            'for %s', request.url)
                return stale

            if response.status_code in self._cache_allowable_codes:
                self.cache.save_response(cache_key, response)
            response.from_cache = False
            return response

        response, timestamp = self.cache.get_response_and_time(cache_key)
        if response is None:
            return send_request_and_cache_response()

        if self._cache_expire_after is not None:
            is_expired = datetime.utcnow() - timestamp > self._cache_expire_after
            if is_expired:
                self.cache.delete(cache_key)
                # try and get a fresh response, but if that fails reuse the
                # stale one
                return send_request_and_cache_response(stale=response)

        # dispatch hook here, because we've removed it before pickling
        response.from_cache = True
        response = dispatch_hook('response', request.hooks, response, **kwargs)
        return response


def basecache_delete(self, key):
    # We don't really delete; we instead set the timestamp to
    # datetime.min. This way we can re-use stale values if the backend
    # fails
    try:
        if key not in self.responses:
            key = self.keys_map[key]
        self.responses[key] = self.responses[key][0], datetime.min
    except KeyError:
        return

from requests_cache.backends.base import BaseCache
BaseCache.delete = basecache_delete

上面的CachedSession子类绕过了original ^{} method,而是直接转到原始的requests.Session.send()方法,以返回现有的缓存值,即使超时已过,但后端已失败。为了将超时值设置为0,删除被禁用,因此如果新请求失败,我们仍然可以重用旧值。在

使用FallbackCachedSession而不是常规的CachedSession对象。在

如果要使用requests_cache.install_cache(),请确保在session_factory关键字参数中将{}传递给该函数:

^{pr2}$

我的方法比在我把上面的代码组合在一起一段时间后实现的requests_cache要全面一些;我的版本将返回到一个过时的响应中,即使您之前明确地将其标记为deleted。在

试着这样做:

class UnreliableAPIClient:
  def __init__(self):
    self.some_api_method_cached = {} # we will store results here

  def some_api_method(self, param1, param2)
    params_hash = "{0}-{1}".format(param1, param2) # need to identify input
    try:
      result = do_call_some_api_method_with_fail_probability(param1, param2)
      self.some_api_method_cached[params_hash] = result # save result
    except:
      result = self.some_api_method_cached[params_hash] # resort to cached result
      if result is None:
        raise # reraise exception if nothing cached
    return result

当然,您可以用它来制作简单的装饰器,由您决定http://www.artima.com/weblogs/viewpost.jsp?thread=240808

相关问题 更多 >