基于 this answer通过@bossylobster,我已经成功地实现了一个与 GMail API 连接的 cron 作业。目前我的代码中有 user_id 和电子邮件地址,但是我正在构建一个应用程序,它应该在用户列表中运行。
这种情况下的问题是,当我在 CredentialsModel 上运行循环时,我没有用户的电子邮件地址。由于我使用的是 webapp 2 中的用户模型(基于 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))
最佳答案
特定于 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'
关于python - 根据 user_id 获取 Google 帐户电子邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29849051/