使用 Google people API 和 python 将某些字段添加到我的联系人中

问题描述 投票:0回答:1

我使用 People API 来创建联系人、更新联系人、获取联系人并将其删除。我想在创建联系人时添加更多字段,但似乎没有添加它们。 我想添加国家/地区代码、辅助号码、城市和职位。我已经尝试实现文档中的内容。职务位于职业字段中,国家/地区代码位于 canonicalForm 字段下的电话号码字段中,城市位于地址字段中。尽管进行了必要的更改,但当我创建新联系人时,这些字段并未填充。我知道这一点是因为我搜索了该联系人并且错过了这些字段。要么是我在创建联系人时遗漏了某些内容,要么是我执行了错误的搜索(尽管它确实会显示结果,所以我不知道这会怎样)

这是我的createcontact.py

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/contacts"]

CREDENTIALS_FILE_PATH = r'/credentials.json'
def create_new_contact(first_name, phone_number, job_title, company, email, city, primaryNumberCC):
  creds = None
  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_FILE_PATH, 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())

  try:
    service = build("people", "v1", credentials=creds)
    service.people().createContact(body={
      "names": [{"givenName": first_name}], 
      "phoneNumbers": [{'value': phone_number,'canonicalForm': primaryNumberCC}],
      "occupations":[{'value':job_title}],
      "organizations":[{'title':company}],
      "emailAddresses":[{'value':email}],
      "addresses": [{"city": city}], 
      }).execute()
    
  except HttpError as err:
    print(err)

这是我搜索联系人的方式。

import os
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# Define the scopes required for accessing the People API
SCOPES = ['https://www.googleapis.com/auth/contacts']

def get_credentials():
    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')
    # 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())
    return creds

def get_contact_resource_by_name(name):
    creds = get_credentials()
    service = build('people', 'v1', credentials=creds)
    
    # Perform a search query using the contact's name
    results = service.people().searchContacts(query=name, readMask="names").execute()
    
    if 'results' in results:
        if len(results['results']) > 0:
            # Extract the resource name of the first matching contact
            print(results)
            return results['results'][0]['person']['resourceName']
    
    return None
python flask google-people-api
1个回答
0
投票

我认为你的功能

create_new_contact
有效。但是,你说
Despite making the necessary changes, when I create a new contact, these fields aren't populated. I know this because I perform a search of that contact and I miss these fields.
。当我看到你的
get_contact_resource_by_name
时,你的函数
get_contact_resource_by_name
仅返回
names
的字段。我担心这可能是原因。如果我的理解正确的话,下面的修改如何?

修改后的脚本:

在此修改中,修改了

get_contact_resource_by_name

def get_contact_resource_by_name(name):
    creds = get_credentials()
    service = build('people', 'v1', credentials=creds)

    # Perform a search query using the contact's name
    results = service.people().searchContacts(query=name, readMask="names,phoneNumbers,occupations,organizations,emailAddresses,addresses").execute()

    if 'results' in results:
        if len(results['results']) > 0:
            # Extract the resource name of the first matching contact
            print(results)
            return results['results'][0]['person']['resourceName']

    return None
  • 在此修改中,当给出
    first_name
    create_new_contact(first_name, phone_number, job_title, company, email, city, primaryNumberCC)
    值作为
    get_contact_resource_by_name(name)
    的参数时,返回包括
    names,phoneNumbers,occupations,organizations,emailAddresses,addresses
    的字段的正确值。

参考:

© www.soinside.com 2019 - 2024. All rights reserved.