为什么我的示例googleapi代码(python,admin,directory\u v1)上的503服务不可用?

2024-06-16 14:11:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个管理Google帐户,有权为我的大学创建自定义域用户(example@stu.najah.edu)。 我想编写一个python脚本来自动完成这项任务,所以我使用Google的API来实现这一点。 我遵循了本教程(https://github.com/googleapis/google-api-python-client/blob/master/docs/oauth-server.md) 做了一切。但是仍然从python得到以下异常:

/Users/osamaabuomar/projects/.virtualenvs/gsuite-api-demo/bin/python /Users/osamaabuomar/projects/gsuite-api-demo/quickstart.py
Getting the first 10 users in the domain
Traceback (most recent call last):
  File "/Users/osamaabuomar/projects/gsuite-api-demo/quickstart.py", line 32, in <module>
    main()
  File "/Users/osamaabuomar/projects/gsuite-api-demo/quickstart.py", line 19, in main
    results = service.users().list(customer='my_customer', maxResults=10, orderBy='email').execute()
  File "/Users/osamaabuomar/projects/.virtualenvs/gsuite-api-demo/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/osamaabuomar/projects/.virtualenvs/gsuite-api-demo/lib/python3.7/site-packages/googleapiclient/http.py", line 856, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 503 when requesting https://www.googleapis.com/admin/directory/v1/users?customer=my_customer&maxResults=10&orderBy=email&alt=json returned "Service unavailable. Please try again">

Process finished with exit code 1

这是我的python代码

^{pr2}$

Tags: inpyapidemolinevirtualenvscustomerusers
1条回答
网友
1楼 · 发布于 2024-06-16 14:11:02

问题是我没有设置委派,正如DalmTo所提到的那样。 这是我完整的工作代码:

from __future__ import print_function
from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user', ]

SERVICE_ACCOUNT_FILE = './quickstart-1570011757324-2bfbc3d902b9.json'


def main():
    credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    delegated_credentials = credentials.with_subject('admin@najah.edu')

    service = googleapiclient.discovery.build('admin', 'directory_v1', credentials=delegated_credentials)

    # Call the Admin SDK Directory API
    print('Getting the first 10 users in the domain')
    results = service.users().list(customer='my_customer', maxResults=10, orderBy='email').execute()
    users = results.get('users', [])

    if not users:
        print('No users in the domain.')
    else:
        print('Users:')
        for user in users:
            print(u'{0} ({1})'.format(user['primaryEmail'],
                                      user['name']['fullName']))


if __name__ == '__main__':
    main()

注意credentials.with_subject('admin@domain.com')部分。在

相关问题 更多 >