简体   繁体   English

如何让 Google admin_sdk 上的所有用户?

[英]How can I get all users on Google admin_sdk?

I need to list all users in my domain, but I can't because my domain there are more then 500 users and the default limit per page is 500. In this example below (the google Quickstart example) How could I list all my 1000 users?我需要列出我域中的所有用户,但我不能,因为我的域有超过 500 个用户,并且每页的默认限制是 500。在下面的这个例子中(谷歌快速入门示例)我怎么能列出我所有的 1000用户? I've already read about Nextpagetoken, but I don't know how I can get or implement it.我已经阅读过 Nextpagetoken,但我不知道如何获取或实现它。 Somebody could help me please?有人可以帮助我吗?

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()

You have to request the different pages iteratively.您必须迭代地请求不同的页面。 You can use a while loop for this.您可以为此使用while循环。

There are two different ways to do this.有两种不同的方法可以做到这一点。

Method 1. list_next:方法一、list_next:

  • Request the first page.请求第一页。
  • Start a while loop that checks if request exists.启动一个while循环来检查request是否存在。
  • Call successive pages using list_next method.使用list_next方法调用连续页面。 This method can be used to retrieve successive pages, based on the request and response from previous page.此方法可用于根据前一页的requestresponse检索连续页面。 With this, you don't need to use pageToken .有了这个,你不需要使用pageToken
  • If a next page doesn't exist, request will return None , so the loop will end.如果下一页不存在, 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']))

Method 2. pageToken:方法二、pageToken:

  • Request the first page (without using the parameter pageToken ).请求第一页(不使用参数pageToken )。
  • Retrieve the property nextPageToken from the response to the first request.从对第一个请求的响应中检索属性nextPageToken
  • Start a while loop that checks if nextPageToken exists.启动一个while循环,检查nextPageToken是否存在。
  • Inside the while loop request successive pages using the nextPageToken retrieved in last response.while循环内,使用在最后一个响应中检索到的nextPageToken请求连续页面。
  • If there's no next page, nextPageToken will not be populated, so the loop will end.如果没有下一页,则不会填充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']))

Note:笔记:

  • In both methods, users from current iteration are added to the main users list, using extend .在这两种方法中,来自当前迭代的用户都被添加到主users列表中,使用extend

Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM