【问题标题】:Python retries on all exceptions except a list of exceptionsPython 重试除异常列表之外的所有异常
【发布时间】:2021-09-08 19:01:10
【问题描述】:

大多数指南和帖子都在讨论相反的情况,即您决定提前重试哪些异常。也许我想错了,但是例如,我正在尝试获取 google 服务帐户凭据

 def get_google_credentials(self, google_creds_dict):        
     SCOPES = [
         'https://www.googleapis.com/auth/drive.readonly',
         'https://www.googleapis.com/auth/drive.file',
         'https://www.googleapis.com/auth/spreadsheets',
     ]
        
     credentials = service_account.Credentials.from_service_account_info(google_creds_dict, scopes=SCOPES)
        
     return credentials

由于我知道它返回 ValueError,我想我只想重试其他异常

【问题讨论】:

  • 只需添加多个例外 - try: do stuff; except ValueError: pass; except IndexError: do stuff

标签: python retry-logic


【解决方案1】:

对您想要通过的特定异常使用except <type>: 块,然后对所有应该重试的异常使用通用except:。然后将其放入 while 循环中以使其继续尝试。

import time

def get_google_credentials(self, google_creds_dict):   
    SCOPES = [
        'https://www.googleapis.com/auth/drive.readonly',
        'https://www.googleapis.com/auth/drive.file',
        'https://www.googleapis.com/auth/spreadsheets',
    ]

    while True:
        try:
            return service_account.Credentials.from_service_account_info(google_creds_dict, scopes=SCOPES)
        except ValueError as e:
            # pass ValueError through
            raise e from None
        except:
            # retry on any other error
            time.sleep(1)        

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 2012-11-02
    • 2016-05-18
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多