微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Google admin_sdk 上获取所有用户? 方法 1. list_next:方法2.pageToken:注意:参考:

如何解决如何在 Google admin_sdk 上获取所有用户? 方法 1. list_next:方法2.pageToken:注意:参考:

我需要列出我域中的所有用户,但我不能,因为我的域有超过 500 个用户,每页的认限制是 500。在下面的这个例子中(谷歌快速入门示例)我怎么能列出我所有的 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()

解决方法

您必须反复请求不同的页面。您可以为此使用 while 循环。

有两种不同的方法可以做到这一点。

方法 1. list_next:

  • 请求第一页。
  • 启动一个 while 循环,检查 request 是否存在。
  • 使用 list_next 方法调用连续页面。此方法可用于根据前一页的 requestresponse 检索连续页面。有了这个,您就不需要使用 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:

  • 请求第一页(不使用参数 pageToken)。
  • 从对第一个请求的响应中检索属性 nextPageToken
  • 启动一个 while 循环,检查 nextPageToken 是否存在。
  • while 循环中,使用上次响应中检索到的 nextPageToken 请求连续页面。
  • 如果没有下一页,则不会填充 nextPageToken,因此循环将结束。
def listUsers(service):
    response = service.users().list(customer='my_customer',orderBy='email').execute()
    users = response.get('users',[])
    nextPageToken = response.get('nextPageToken',"")
    while nextPageToken:
        response = service.users().list(customer='my_customer',orderBy='email',pageToken=nextPageToken).execute()
        nextPageToken = response.get('nextPageToken',"")
        users.extend(response.get('users',user['name']['fullName']))

注意:

  • 在这两种方法中,使用 extend 将当前迭代中的用户添加到主 users 列表中。

参考:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。