Google API客户端(Python):是否可以将BatchHttpRequest与ETag缓存一起使用

时间:2016-06-13 19:07:40

标签: python google-api-client httplib2 youtube-data-api

我正在使用YouTube数据API v3。

是否可以制作一个大BatchHttpRequest(例如,参见here),并在httplib2级别使用ETag进行本地缓存(例如,请参阅here )?

ETags适用于单个查询,我不明白它们是否也适用于批量请求。

1 个答案:

答案 0 :(得分:3)

<强> TL; DR

  • BatchHttpRequest不能与缓存一起使用

这是

首先让我们看一下初始化BatchHttpRequest的方法:

from apiclient.http import BatchHttpRequest

def list_animals(request_id, response, exception):
  if exception is not None:
    # Do something with the exception
    pass
  else:
    # Do something with the response
    pass

def list_farmers(request_id, response):
  """Do something with the farmers list response."""
  pass

service = build('farm', 'v2')

batch = service.new_batch_http_request()

batch.add(service.animals().list(), callback=list_animals)
batch.add(service.farmers().list(), callback=list_farmers)


batch.execute(http=http)

其次,了解ETags的使用方式:

from google.appengine.api import memcache
http = httplib2.Http(cache=memcache)

现在让我们分析一下:

观察BatchHttpRequest示例的最后一行: batch.execute(http=http) ,现在检查source code是否执行,它调用_refresh_and_apply_credentials,它应用http对象我们通过它。

def _refresh_and_apply_credentials(self, request, http):
    """Refresh the credentials and apply to the request.
    Args:
      request: HttpRequest, the request.
      http: httplib2.Http, the global http object for the batch.
    """
    # For the credentials to refresh, but only once per refresh_token
    # If there is no http per the request then refresh the http passed in
    # via execute()

这意味着,执行带有http的调用,可以传递给你创建的ETag http:

http = httplib2.Http(cache=memcache)
# This would mean we would get the ETags cached http
batch.execute(http=http)

更新1

也可以尝试使用自定义对象:

from googleapiclient.discovery_cache import DISCOVERY_DOC_MAX_AGE
from googleapiclient.discovery_cache.base import Cache
from googleapiclient.discovery_cache.file_cache import Cache as FileCache

custCache = FileCache(max_age=DISCOVERY_DOC_MAX_AGE)
http = httplib2.Http(cache=custCache)
# This would mean we would get the ETags cached http
batch.execute(http=http)

因为,这只是http2 lib中评论的预感:

"""If 'cache' is a string then it is used as a directory name for
        a disk cache. Otherwise it must be an object that supports the
        same interface as FileCache.

结论更新2:

再次验证google-api-python源代码后,我看到BatchHttpRequest已修复为'POST'请求,其内容类型为multipart/mixed;.. - {{3} }。

给出一个事实的线索,即BatchHttpRequest对于POST数据有用,然后再对其进行处理。

现在,请记住这一点,只有满足以下条件时才能观察source code request方法使用的内容:_updateCache

  1. 请求位于["GET", "HEAD"]response.status == 303redirect request
  2. ElSE - response.status in [200, 203] and method in ["GET", "HEAD"]
  3. 或 - if response.status == 304 and method == "GET"
  4. 这意味着,BatchHttpRequest无法用于缓存。