python中的GoogleAppClient,使用updateContact返回403

2024-09-25 00:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从谷歌的API获取联系人列表,然后更新其中的一些联系人。在运行updateContact函数时,我每次都会收到403个错误Request person.etag is different than the current person.etag. Clear local cache and get the latest person."
我正在使用以下代码读取联系人的etag:

service = build('people', 'v1', credentials=creds)
results = service.people().connections().list(
        resourceName='people/me',
        pageSize=100,
        personFields='names,emailAddresses').execute()
connections = results.get('connections', [])

然后,对于connections中的每个contact,我尝试更改联系人的givenName和familyName:

service.people().updateContact(resourceName="contact's resource name",
                              updatePersonFields="names",
                              body={
                                  "etag": "contact's etag",
                                  "names": [
                                    {
                                      "familyName": "new family name",
                                      "givenName": "new given name"
                                    }
                                  ]
                                }
                              ).execute()

联系人的etagresourceName来自连接的列表响应。
例如:

print(connections[0])
{'resourceName': 'people/<resource_number>',
 'etag': 'etag string',
 'names': [{'metadata': {'primary': True,
    'source': {'type': 'CONTACT', 'id': 'id number'}},
   'displayName': 'x',
   'familyName': 'x',
   'givenName': 'x',
   'displayNameLastFirst': 'x',
   'unstructuredName': 'x'}]}

Tags: thename列表namesservicecontact联系人people
1条回答
网友
1楼 · 发布于 2024-09-25 00:31:25

运行准确的代码确实有效

我运行了您的代码并基于Google People Python Quickstart,同时只更改了两件事:

  1. 权限

  2. 添加代码

    SCOPES = ['https://www.googleapis.com/auth/contacts']
    
    ...
    
    service = build('people', 'v1', credentials=creds)
    
    results = service.people().connections().list(
        resourceName='people/me',
        pageSize=5,
        personFields='names,emailAddresses').execute()
    connections = results.get('connections', [])
    
    for contact in connections:
        service.people().updateContact(resourceName=contact['resourceName'],
                                       updatePersonFields="names",
                                       body={
                                           "etag": contact['etag'],
                                           "names": [
                                               {
                                                   "familyName": "new family name",
                                                   "givenName": "new given name"
                                               }
                                           ]
                                       }
                                       ).execute()
    

相关问题 更多 >