通过


使用 Microsoft Graph 列出 Python 应用中的用户

在本文中,将扩展在 使用 Microsoft Graph 生成 Python 应用时创建的应用程序,并使用 Microsoft Graph 用户 API 进行仅限应用的身份验证。 使用 Microsoft Graph 列出组织中的用户。

  1. 将以下函数添加到 graph.py

    async def get_users(self):
        query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
            # Only request specific properties
            select = ['displayName', 'id', 'mail'],
            # Get at most 25 results
            top = 25,
            # Sort by display name
            orderby= ['displayName']
        )
        request_config = UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(
            query_parameters=query_params
        )
    
        users = await self.app_client.users.get(request_configuration=request_config)
        return users
    
  2. main.py 中的空list_users函数替换为以下内容。

    async def list_users(graph: Graph):
        users_page = await graph.get_users()
    
        # Output each users's details
        if users_page and users_page.value:
            for user in users_page.value:
                print('User:', user.display_name)
                print('  ID:', user.id)
                print('  Email:', user.mail)
    
            # If @odata.nextLink is present
            more_available = users_page.odata_next_link is not None
            print('\nMore users available?', more_available, '\n')
    
  3. 运行应用并选择选项 2 以列出用户。

    Please choose one of the following options:
    0. Exit
    1. Display access token
    2. List users
    3. Make a Graph call
    2
    User: Adele Vance
      ID: 05fb57bf-2653-4396-846d-2f210a91d9cf
      Email: AdeleV@contoso.com
    User: Alex Wilber
      ID: a36fe267-a437-4d24-b39e-7344774d606c
      Email: AlexW@contoso.com
    User: Allan Deyoung
      ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0
      Email: AllanD@contoso.com
    User: Bianca Pisani
      ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49
      Email: None
    User: Brian Johnson (TAILSPIN)
      ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4
      Email: BrianJ@contoso.com
    
    ...
    
    More users available? True
    

代码说明

请考虑 函数中的 get_users 代码。

  • 它获取用户的集合
  • 它使用 $select 请求特定属性
  • 它使用 $top 来限制返回的用户数
  • 它使用 $orderBy 对响应进行排序

后续步骤