people.connections.list没有使用Python客户端库

时间:2016-07-31 02:25:48

标签: python google-people

我尝试使用Python客户端库以编程方式访问我个人Google帐户中的联系人列表

这是一个在没有用户输入的服务器上运行的脚本,因此我将其设置为使用我设置的服务帐户的凭据。我的Google API控制台设置如下所示。

enter image description here

我使用以下基本脚本,摘自API文档中提供的示例 -

import json
from httplib2 import Http

from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build

# Only need read-only access
scopes = ['https://www.googleapis.com/auth/contacts.readonly']

# JSON file downloaded from Google API Console when creating the service account
credentials = ServiceAccountCredentials.from_json_keyfile_name(
    'keep-in-touch-5d3ebc885d4c.json', scopes)

# Build the API Service
service = build('people', 'v1', credentials=credentials)

# Query for the results
results = service.people().connections().list(resourceName='people/me').execute()

# The result set is a dictionary and should contain the key 'connections'
connections = results.get('connections', [])

print connections  #=> [] - empty!

当我点击API时,它会返回一个没有任何'连接的结果集。键。具体来说,它返回 -

>>> results
{u'nextSyncToken': u'CNP66PXjKhIBMRj-EioECAAQAQ'}

是否有与我的设置或代码有关的内容不正确?有没有办法查看响应HTTP状态代码或获取有关它尝试做什么的更多详细信息?

谢谢!

附注:当我使用the "Try it!" feature in the API docs尝试时,它会正确返回我的联系人。虽然我怀疑使用客户端库而是依赖于OAuth的用户授权

4 个答案:

答案 0 :(得分:6)

personFields 掩码是必需的。指定一个或多个有效路径。有效路径记录在https://developers.google.com/people/api/rest/v1/people.connections/list/

此外,使用字段掩码指定部分响应中包含哪些字段。

而不是:

results = service.people().connections().list(resourceName='people/me').execute() 

...尝试:

results = service.people().connections().list(resourceName='people/me',personFields='names,emailAddresses',fields='connections,totalItems,nextSyncToken').execute() 

答案 1 :(得分:2)

这是一个有效的演示。我刚刚测试了它。 Python 3.5.2

google-api-python-client==1.6.4
httplib2==0.10.3
oauth2client==4.1.2

您可以将其保存到demo.py,然后运行它。我离开了create_contact函数,以防您可能想要使用它,并且还有一个关于API使用的示例。

CLIENT_IDCLIENT_SECRET是环境变量,所以我不会在代码中意外地分享它。

"""Google API stuff."""

import httplib2
import json
import os

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run_flow


CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
SCOPE = 'https://www.googleapis.com/auth/contacts'
USER_AGENT = 'JugDemoStackOverflow/v0.1'

def make_flow():
    """Make flow."""
    flow = OAuth2WebServerFlow(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        scope=SCOPE,
        user_agent=USER_AGENT,
    )
    return flow


def get_people():
    """Return a people_service."""
    flow = make_flow()
    storage = Storage('info.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage)

    http = httplib2.Http()
    http = credentials.authorize(http)
    people_service = build(serviceName='people', version='v1', http=http)
    return people_service


def create_contact(people, user):
    """Create a Google Contact."""
    request = people.createContact(
        body={
            'names': [{'givenName': user.name}],
            'phoneNumbers': [
                {'canonicalForm': user.phone, 'value': user.phone}],
        }
    )
    return request.execute()


def demo():
    """Demonstrate getting contacts from Google People."""
    people_service = get_people()
    people = people_service.people()
    connections = people.connections().list(
        resourceName='people/me',
        personFields='names,emailAddresses,phoneNumbers',
        pageSize=2000,
    )
    result = connections.execute()
    s = json.dumps(result)
    # with open('contacts.json', 'w') as f:
    #     f.write(s)
    return s


if __name__ == '__main__':
    print(demo())

答案 2 :(得分:0)

使用服务帐户,在DwD - G Suite域范围的代表团中,必须以这种方式模仿或委派用户

delegate = credentials.create_delegated('user@xxxx.xxx')

答案 3 :(得分:0)

对于其他googlers:使用JS API时遇到同样的问题。

我在我的个人gmail地址上取得了成功,但在我的工作中没有(g-suite)也不在我的辅助Gmail地址上。

无法看到模式。工作人员可能已停用联系人列表。