基于@bossylobster的这个答案,我成功地实现了与GMail API连接的cron作业。目前,我的代码中有user_id和电子邮件地址,但是我正在构建一个应用程序,它应该通过用户列表运行。
在这种情况下,问题是当我在凭据模型上运行循环时,我没有用户的电子邮件地址。由于我使用的是 webapp 2 中的用户模型(基于本教程),因此我也无法在任何地方查找此 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'
有关电子邮件范围,请参阅 Google 的文档。
您可以使用userId="me"调用Gmail API,这意味着,只需使用凭据中经过身份验证的用户的用户ID,而无需指定电子邮件地址/用户ID。 c.f. 文档中 userId 字段的描述:https://developers.google.com/gmail/api/v1/reference/users/labels/list