【发布时间】:2022-11-15 03:23:09
【问题描述】:
我正在尝试使用 Python 中的 Google API 查看组织中所有用户的文件。我有一个具有域范围委派的服务帐户。我正在尝试为每个用户创建委派凭据,以便我可以查看他们的文件。
但是,当我运行下面的代码时,在 for 循环中的这一行:
results = drive_service.files().list(
pageSize=10, fields="").execute()
我收到此错误:
googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/drive/v3/files?pageSize=10&fields=nextPageToken%2C+files%28id%2C+name%29&alt=json returned "Invalid Credentials". Details: "[{'domain': 'global', 'reason': 'authError', 'message': 'Invalid Credentials', 'locationType': 'header', 'location': 'Authorization'}]">
上面不使用委托凭据的同一行工作正常,(所以我知道我有必要的范围并且启用了 Drive API)所以我认为del_creds 有问题。我已经三次检查是否启用了域范围的委派。任何帮助表示赞赏!
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.user.security', 'https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive.readonly']
CREDS = 'service-account-credentials.json'
def main():
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
creds = service_account.Credentials.from_service_account_file(
CREDS, scopes=SCOPES, subject='--my-email--')
service = build('admin', 'directory_v1', credentials=creds)
# Call the Admin SDK Directory API
#print('Getting the first 10 users in the domain')
request = service.users().list(customer='--customer-code--',
orderBy='email')
response = request.execute()
users = response.get('users', [])
while request:
request = service.users().list_next(previous_request=request, previous_response=response)
if request:
response = request.execute()
users.extend(response.get('users', []))
drive_service = build('drive', 'v3', credentials=creds)
results = drive_service.files().list(
pageSize=10, fields="").execute()
items = results.get('files', [])
if not users:
print('No users in the domain.')
else:
for user in users:
email = user['primaryEmail']
del_creds = creds.with_subject(email)
drive_service = build('drive', 'v3', credentials=del_creds)
# Call the Drive v3 API
results = drive_service.files().list(
pageSize=10, fields="").execute()
items = results.get('files', [])
if not items:
print('No files found.')
return
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
【问题讨论】:
标签: python google-drive-api google-admin-sdk