【问题标题】:Cannot add user via google API无法通过 google API 添加用户
【发布时间】:2020-05-16 02:40:33
【问题描述】:

我的名字是阿德里安。我想通过python3通过google admin SDK将用户添加到G套件。

这是我的问题:

我有这个代码:

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']

def createUserConnection():  
   creds = None
   # The file token.pickle 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.pickle'): 
       with open('token.pickle', 'rb') as token:
           creds = pickle.load(token, encoding='Latin-1')
   # 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.pickle', 'wb') as token:
           pickle.dump(creds, token)
   createUserConnection.service = build('admin', 'directory_v1', credentials=creds)


def addUser(name,familyName,usermail):
   print('Adding user '+usermail+' to the G suite')
   #json definition
   userInfo = json.dumps({
   "name" : {
       "givenName": name, 
       "familyName": familyName
   },
   "kind": "admin#directory#user", 
   "primaryEmail": usermail,
   "password": "Welcome1234",
   "changePasswordAtNextLogin": True 
   })
   createUserConnection.service.users().insert(body=userInfo).execute()


if __name__ == '__main__':
   createUserConnection()
   addUser("bla","bla","blabla@24i.com")

当我通过 python3 运行它时,它会再次出现错误。文件“/Users/adrianbardossy/Downloads/google_accounts/python3.7/lib/python3.7/site-packages/googleapiclient/http.py”,第 856 行,正在执行

   raise HttpError(resp, content, uri=self.uri)

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

我试图通过传递用户名 blabla 而不是 blabla@24i.com 来解决,但仍然是同样的问题。基于此处的文档:https://developers.google.com/resources/api-libraries/documentation/admin/directory_v1/python/latest/admin_directory_v1.users.html 用于插入方法。你能帮我解决这个问题吗?

阿德里安

【问题讨论】:

标签: python-3.x google-workspace


【解决方案1】:

我知道这是旧的,但如果你还没有得到它,我会在字段中添加一个 dict 来代替对 JSON 进行任何转换或任何操作:

def get_user_inf(service):
    '''
    This initiates the collection of user data.
    '''

    user_fname = str(input('What is the new hires first name? : '))
    user_lname = str(input('What is the new hires last name? :  '))
    user_email = str(input('What is the new hires email? : '))

    new_user = {
        "name": {
            "givenName": user_fname,
            "fullName": user_fname + " " + user_lname,
            "familyName": user_lname,
        },
        "primaryEmail": user_fname + '.' + user_lname + "@hometownticketing.com",
        "recoveryEmail": user_email,
        "password": "Temp42!!!",
        "changePasswordAtNextLogin": True,
    }

    user = service.users().insert(body=new_user).execute()

【讨论】:

    【解决方案2】:

    这是由于在 service.users().insert()body 参数中输入 JSON 对象字符串引起的。它应该只是一个普通的 python dict。

    代替

    userInfo = json.dumps({
        "name": ...
    

    使用

    userInfo = {
        "name": ...
    

    我也坚持了很长时间,因为文档暗示它应该作为 JSON 对象输入,我将其解释为“JSON 对象编码为字符串”,但我发现它实际上应该只是一个 python对象/字典。

    【讨论】:

      【解决方案3】:

      我在使用 javascript 库时遇到了相同的消息错误 Invalid Input: primary_user_email,据我了解,这意味着 api 在您的正文中找不到 primaryEmail 属性。换句话说:您的 JSON 格式错误。

      这是我对这个问题的看法,我使用 javascript 术语,但它也应该转移到 python :

      如果您使用gapi.client.directory.insert 方法添加用户,您需要将您的主体封装在resource 属性中,您的JSON 变为

      {
          "resource": {
             "name" : {
                 "givenName": "name",
                 "familyName": "familyName"
             },
             "kind": "admin#directory#user",
             "primaryEmail": "usermail",
             "password": "password",
             "changePasswordAtNextLogin": true 
         }
      }
      

      但是,如果您使用 gapi.client.request 方法添加用户,该库将为您封装 JSON,因此您的主体应如下所示:

      {
         "name" : {
             "givenName": "name",
             "familyName": "familyName"
         },
         "kind": "admin#directory#user",
         "primaryEmail": "usermail",
         "password": "password",
         "changePasswordAtNextLogin": true 
      }
      

      对 OP 的简短回答:您正在使用 insert 方法,请尝试将您的 JSON 封装在 resource 属性中。

      希望它对将来偶然发现此错误的人有所帮助

      【讨论】:

      • 这似乎不适用于 python 客户端/库
      猜你喜欢
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 2016-12-19
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多