我注意到在http.py中很多方法都支持 num_retries,我认为这是指数退避的一种实现(以防 API 返回错误)。每次调用 .execute() 方法时都想使用它而不是编写自己的退避算法。但是,它似乎不适用于此代码。有人对以可重用的方式处理此退避有一个方便的想法吗?
from apiclient.discovery import build
import google.auth
from google.auth.transport import requests
from google.auth import iam
from google.oauth2 import service_account
TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
ADMIN_DIRECTORY_SCOPES = [
'https://www.googleapis.com/auth/admin.directory.user.readonly'
]
ADMIN_USER = 'my_gsuite_admin@domain.com'
def delegated_credentials(credentials, subject, scopes):
try:
admin_creds = credentials.with_subject(subject).with_scopes(scopes)
except AttributeError:
request = requests.Request()
credentials.refresh(request)
signer = iam.Signer(request, credentials, credentials.service_account_email)
admin_creds = service_account.Credentials(
signer, credentials.service_account_email, TOKEN_URI,
scopes=scopes, subject=subject
)
except Exception:
raise
return admin_creds
print('Setting up auth')
default_credentials, _ = google.auth.default()
admin_creds = delegated_credentials(
default_credentials, ADMIN_USER, ADMIN_DIRECTORY_SCOPES
)
directory_service = build('admin', 'directory_v1', credentials=admin_creds)
def get_ou(email):
response = directory_service.users().get(
userKey=email,
fields='primaryEmail,orgUnitPath',
num_retries=5
).execute()
print('Directory.users.get: {}'.format(response))
return response['orgUnitPath']
回溯(最近一次通话最后):文件“”,第 1 行,文件“/Users/mryerse001/Documents/GitHub/updateEmail_to_OU_Mappings/main.py”,第 122 行,get_pubsub_messages 成功 = get_ou(email) 文件“/Users/ mryerse001/Documents/GitHub/updateEmail_to_OU_Mappings/main.py”,第 87 行,在 get_ou num_retries=5 文件“/Users/mryerse001/Documents/GitHub/updateEmail_to_OU_Mappings/venv/lib/python3.7/site-packages/googleapiclient/discovery. py",第 717 行,在方法 raise TypeError('Got an unexpected keyword argument "%s"' % name) TypeError: Got an unexpected keyword argument "num_retries"