Skip to main content
 首页 » 编程设计

python之使用 Google People API 的 REST people.get() 中的 userId 参数无效

2025年05月04日10emanlee

根据谷歌的 OAUTH API documentation ,userinfo.profile 和 userinfo.email 范围已被弃用,取而代之的是使用 profile 和 email。有很多 information来自其他 API 用户的关于此转换的信息。

但是,当尝试使用 People API 时,出现此错误:

2016-02-22 13:01:25,044 :Exception on /admin/testbank/settings [GET] 
Traceback (most recent call last): 
  (Flask traceback omitted...) 
  File "/home/somedev/testweb/views/admin_view.py", line 78, in admin_view 
    res_acct_info = people_service.people().get(userId='me').execute() 
  File "/home/somedev/env/lib/python3.4/site-packages/googleapiclient/discovery.py", line 676, in method 
    raise TypeError('Got an unexpected keyword argument "%s"' % name) 
TypeError: Got an unexpected keyword argument "userId" 

查看 Google API sample ,这应该是正确的调用。但是,在库的 discovery.py 中转储 parameters.argmap显示userId不存在。我做错了什么?

(注意:我正在尝试标记 google-people,因为这是 API 页面建议的位置,但我没有足够的代表来标记它。其他人可以添加此标记吗对我来说?)

请您参考如下方法:

事实证明,我一直对我正在阅读的确切代码视而不见...所有这些示例(尤其是 Google 的 example )一直在使用 Google+ API,它确实具有 userId 参数。

作为引用,“旧方法”是使用 oauth2/userinfo 服务:

service = build('oauth2', 'v2', http=http) 
user = users_service.userinfo().get().execute() 
name = user.get('name') 
email = user.get('email') 

您可以使用 Google+ API 获取相同的信息 - 它会起作用,即使用户没有 Google+:

service = discovery.build("plus", "v1", http=http) 
user = service.people().get(userId='me').execute() 
# This assumes that user['emailAddresses'] exists and 
# has at least one element... 
name = user.get('displayName') 
email = user.get('emailAddresses')[0].get("value") 

在撰写本文时,People API 似乎是 released recently (2016 年 2 月 10 日)!没有太多关于它的文档是有道理的......

要使用较新的 People API(并且可能声称来自 Google+ 的清洁),这是获取当前用户信息的正确方法:

service = discovery.build('people', 'v1', http_auth) 
user = people_service.people().get(resourceName='people/me').execute() 
# This assumes that user['names'] and user['emailAddresses'] 
# exists and has at least one element... 
name = user.get('names')[0].get("displayName") 
email = user.get('emailAddresses')[0].get("value") 

resourceName 替换了 People API 中的 userId。它具有相似的目的(识别当前用户或其他用户),但格式不同,如使用 'people/me' 与仅使用 'me' 所示.

Google+ 和较新的 People API 都只需要 email 和 profile 范围。但是,与以前的 userinfo API 不同,您需要手动启用 Google+ API 和/或 People API 才能使用它们。

tl;dr:Google+ API 使用 userId='me',新的 People API 使用 resourceName='people/me',你应该使用这些受支持的 API 之一 - 两者都返回相同的信息,只是格式略有不同!