【问题标题】:Get Google Account email address based on user_id根据 user_id 获取 Google Account 邮箱地址
【发布时间】:2015-07-03 03:36:08
【问题描述】:

基于@bossylobster 的this answer,我已经成功实现了一个与GMail API 连接的cron 作业。目前我的代码中有 user_id 和电子邮件地址,但是我正在构建一个应用程序,它应该在用户列表中运行。

这种情况下的问题是,当我在 CredentialsModel 上运行循环时,我没有用户的电子邮件地址。由于我使用的是 webapp 2 中的 User 模型(基于 this tutorial),因此我也无法在任何地方查找此 ID(据我所知)。

如果我能以某种方式检索带有 user_id 和凭据的电子邮件地址,或者在授予权限的那一刻将电子邮件地址和 user_id 保存在用户模型中......处理这个问题的最佳方法是什么?

我的授权码:

http = httplib2.Http(memcache)
service = discovery.build("gmail", "v1", http=http)
decorator = OAuth2Decorator(client_id=settings.CLIENT_ID,
                        client_secret=settings.CLIENT_SECRET,
                        scope=settings.SCOPE)

class getPermissions(webapp2.RequestHandler):
  @decorator.oauth_aware
  def get(self):
    template_values = {
    'url': decorator.authorize_url(),
    'has_credentials': decorator.has_credentials()
    }
    self.response.out.write(template.render('templates/auth.html', template_values))

【问题讨论】:

  • “在 CredentialsModel 上运行循环”是什么意思?
  • 调用 CredentialsModel 中的所有实体并使用它们来执行我的 API 调用。这解释清楚了吗?

标签: python google-app-engine gmail-api


【解决方案1】:

Gmail API 特定方法

您可以致电users.getProfile() 获取用户的电子邮件地址:

user_profile = service.users().getProfile(userId='me').execute()
user_email = user_profile['emailAddress']

此方法的优点是不需要您添加任何额外的 API 范围。

通用方法

如果您将email 添加到您的 OAuth 范围列表中,那么您的凭据对象将包括用户的电子邮件地址:

try:
  print credentials.id_token['email']
except KeyError:
  print 'Unknown email'

Google's docs for the email scope

【讨论】:

    【解决方案2】:

    您可以使用 userId="me" 调用 Gmail API,这意味着,只需使用凭据中经过身份验证的用户的 userId -- 无需指定电子邮件地址/userId。参考文献文档中 userId 字段的描述: https://developers.google.com/gmail/api/v1/reference/users/labels/list

    【讨论】:

    • 谢谢,这将解决大部分问题。不过,我想知道我的应用程序上的哪些用户与哪些凭据相匹配。是不是例如可靠/推荐保存 user_id 并在注册时直接调用 Google People API?
    猜你喜欢
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    相关资源
    最近更新 更多