Почему я получаю сервис 503, недоступный для моего примера кода API Google (python, admin, directory_v1)? - PullRequest
1 голос
/ 03 октября 2019

У меня есть учетная запись администратора Google и доступ к созданию пользовательских доменов для моего университета (example@stu.najah.edu). Я хочу написать скрипт Python для автоматизации этой задачи, поэтому я использую API Google для этого. Я следовал этому руководству (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

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


def main():
    SCOPES = ['https://www.googleapis.com/auth/admin.directory.user',
              'https://www.googleapis.com/auth/admin.directory.customer']

    SERVICE_ACCOUNT_FILE = './quickstart-1570011757324-0609ceb3ce31.json'

    credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

    service = googleapiclient.discovery.build('admin', 'directory_v1', credentials=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()

1 Ответ

1 голос
/ 04 октября 2019

Проблема была в том, что я пропустил настройку делегирования, как упоминалось 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') часть.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...