Как я могу получить всех пользователей в Google admin_sdk?

Мне нужно перечислить всех пользователей в моем домене, но я не могу, потому что в моем домене более 500 пользователей, а ограничение по умолчанию на страницу составляет 500. В этом примере ниже (пример быстрого запуска Google) Как я могу перечислить все мои 1000 пользователи? Я уже читал о Nextpagetoken, но не знаю, как его получить или реализовать. Кто-нибудь может мне помочь?

from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']

def main():
    """Shows basic usage of the Admin SDK Directory API.
    Prints the emails and names of the first 10 users in the domain.
    """
    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.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    service = build('admin', 'directory_v1', credentials=creds)

    # Call the Admin SDK Directory API
    print('Getting the first 10 users in the domain')
    results = service.users().list(customer='my_customer', maxResults=1000, 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()

person Lailton Montenegro    schedule 18.05.2021    source источник


Ответы (1)


Вы должны запросить разные страницы итеративно. Для этого можно использовать цикл while.

Есть два разных способа сделать это.

Способ 1. list_next:

  • Запрос первой страницы.
  • Запустите цикл while, который проверяет, существует ли request.
  • Вызов последовательных страниц с помощью метода list_next. Этот метод можно использовать для извлечения последовательных страниц на основе request и response с предыдущей страницы. При этом вам не нужно использовать pageToken.
  • Если следующей страницы не существует, request вернет None, поэтому цикл завершится.
def listUsers(service):
    request = service.users().list(customer='my_customer', maxResults=500, 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', []))
    if not users:
        print('No users in the domain.')
    else:
        for user in users:
            print(u'{0} ({1})'.format(user['primaryEmail'],user['name']['fullName']))

Способ 2. Токен страницы:

  • Запрос первой страницы (без использования параметра pageToken).
  • Получите свойство nextPageToken из ответа на первый запрос.
  • Запустите цикл while, который проверяет, существует ли nextPageToken.
  • Внутри цикла while запрашивайте последовательные страницы, используя nextPageToken, полученный в последнем ответе.
  • Если следующей страницы нет, nextPageToken не будет заполнено, поэтому цикл завершится.
def listUsers(service):
    response = service.users().list(customer='my_customer', maxResults=500, orderBy='email').execute()
    users = response.get('users', [])
    nextPageToken = response.get('nextPageToken', "")
    while nextPageToken:
        response = service.users().list(customer='my_customer', maxResults=500, orderBy='email', pageToken=nextPageToken).execute()
        nextPageToken = response.get('nextPageToken', "")
        users.extend(response.get('users', []))
    if not users:
        print('No users in the domain.')
    else:
        for user in users:
            print(u'{0} ({1})'.format(user['primaryEmail'],user['name']['fullName']))

Примечание:

  • В обоих методах пользователи из текущей итерации добавляются в основной список users с помощью extend. .

Ссылка:

person Iamblichus    schedule 19.05.2021
comment
Большое спасибо lamblichus. С помощью двух методов можно было перечислить всех пользователей. - person Lailton Montenegro; 19.05.2021