如果出错,如何重试urlfetch.fetch几次?

LA_*_*LA_ 5 python google-app-engine exception-handling

通常GAE无法上传文件,我收到以下错误:

ApplicationError: 2
Traceback (most recent call last):
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 636, in __call__
    handler.post(*groups)
  File "/base/data/home/apps/picasa2vkontakte/1.348093606241250361/picasa2vkontakte.py", line 109, in post
    headers=headers
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/urlfetch.py", line 260, in fetch
    return rpc.get_result()
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 592, in get_result
    return self.__get_result_hook(self)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/urlfetch.py", line 355, in _get_fetch_result
    raise DownloadError(str(err))
DownloadError: ApplicationError: 2
Run Code Online (Sandbox Code Playgroud)

如果出现此类错误,我该如何进行重试?

        try:
            result = urlfetch.fetch(url=self.request.get('upload_url'), 
                                    payload=''.join(data),
                                    method=urlfetch.POST,
                                    headers=headers
                                    )
        except DownloadError:
            # how to retry 2 more times?
        # and how to verify result here?
Run Code Online (Sandbox Code Playgroud)

Dre*_*ars 9

如果可以,请将此工作移至任务队列中.当任务失败时,它们会自动重试.如果它们继续失败,系统会逐渐将重试频率退回到每小时一次的速度.这是一种简单的方法来处理对速率受限服务的API请求,而无需实现一次性重试逻辑.

如果你真的需要同步处理请求,这样的事情应该有效:

for i in range(3):
  try:
    result = urlfetch.fetch(...)
    # run success conditions here
    break
  except DownloadError:
    #logging.debug("urlfetch failed!")
    pass
Run Code Online (Sandbox Code Playgroud)

您还可以传递deadline=10给urlfetch.fetch以将默认超时截止时间加倍.