【问题标题】:Adding multiple users JSON for Google Directory API (Python)为 Google Directory API (Python) 添加多个用户 JSON
【发布时间】:2021-09-20 10:51:20
【问题描述】:

当我尝试添加用户时: 这样我只能添加一个用户,但是我需要从 JSON 文件中添加多个用户。

req =  [
            {
                "primaryEmail": "first.user@mydomain.com",
                "name": {
                            "givenName": "UserName",
                            "familyName": "UserLastName"
                        },
                "suspended": False,
                "password": "my password",
                "hashFunction": "SHA-1",
                "changePasswordAtNextLogin": False,
                "agreedToTerms": True,
                "ipWhitelisted": False                
            },
            {
                "primaryEmail": "second.user@exnesstest.com",
                "name": {
                            "givenName": "FirstName",
                          "familyName": "LastName"
                       },
                "suspended": False,
                "password": "my password",
                "hashFunction": "SHA-1",
                "changePasswordAtNextLogin": False,
                "agreedToTerms": True,
                "ipWhitelisted": False               

            }
        ]
users = service.users().insert(body=req).execute()

我收到一些错误,例如:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://admin.googleapis.com/admin/directory/v1/users?alt=json returned "Invalid Input: primary_user_email">

这种方式如何添加多个用户?

【问题讨论】:

    标签: google-admin-sdk


    【解决方案1】:

    如果您想在一个 API 调用中发送多个操作,则必须使用 BatchRequest。以下是 google 提供的 Python 文档中的一个示例

    def list_animals(request_id, response, exception):
      if exception is not None:
        # Do something with the exception
        pass
      else:
        # Do something with the response
        pass
    
    def list_farmers(request_id, response):
      """Do something with the farmers list response."""
      pass
    
    service = build('farm', 'v2')
    
    batch = service.new_batch_http_request()
    
    batch.add(service.animals().list(), callback=list_animals)
    batch.add(service.farmers().list(), callback=list_farmers)
    batch.execute()
    

    您可以在此处阅读有关该方法的更多信息:https://developers.google.com/admin-sdk/directory/v1/guides/batch

    或者直接使用github仓库(示例出处):https://googleapis.github.io/google-api-python-client/docs/batch.html

    您唯一需要注意的是每秒/分钟/小时发送的请求阈值,但如果您超过限制,谷歌会出错,您必须使用 Exponential Backoff 限制请求

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-24
      • 2015-08-10
      • 2017-05-28
      • 2018-12-18
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多