如何在谷歌应用引擎中使用带有oauth2的deferred.defer?

时间:2014-07-30 10:30:58

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

我有装饰师:

http = httplib2.Http()
service = discovery.build('gmail', 'v1', http=http)
# Creating decorator for OAuth2 account.
decorator = appengine.oauth2decorator_from_clientsecrets(
    CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/gmail.readonly',
    message=MISSING_CLIENT_SECRETS_MESSAGE)

使用它的课程:

class CSVGeneratorHandler(webapp2.RedirectHandler):
    @decorator.oauth_required
    def get(self):
        http = decorator.http()
        first_messages = service.users().messages().list(userId='me').execute(http=http)
        template = JINJA_ENVIRONMENT.get_template('templates/success.html')
        self.response.write(template.render({}))

这很有效。

但是当我尝试将API请求 service.users()。messages()。list(userId =' me')。执行(http = http)移动到任务(使用deferred.defer(get_mails))我收到错误:"需要登录"。

我知道get_mails函数必须从主程序接收上下文或/和凭据。但我不明白该怎么做。

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

几个小时后我找到了答案。

首先,您需要将凭据保存到某个地方。因为我们GAE我们有特殊的字段类型:

from oauth2client.appengine import StorageByKeyName  
from google.appengine.ext import db

class CredentialsModel(db.Model):
  credentials = CredentialsProperty()

下一步是设置不带装饰器的auth,然后才将任务发送到队列:

    user = users.get_current_user()
    flow = flow_from_clientsecrets(os.path.join(os.path.dirname(os.path.realpath(__file__)), CLIENT_SECRETS),
                           scope='https://www.googleapis.com/auth/gmail.readonly',
                           redirect_uri='http://127.0.0.1:8080/success')
    auth_uri = str(flow.step1_get_authorize_url())
    code = self.request.get('code')
    if not code:
        return self.redirect(auth_uri)
    credentials = flow.step2_exchange(code)

    storage = StorageByKeyName(CredentialsModel, user.user_id(), 'credentials')
    storage.put(credentials)

    deferred.defer(get_mails, user.user_id())

不要忘记在延期功能中获取凭证!

def get_mails(user_id):
    storage = StorageByKeyName(CredentialsModel, user_id, 'credentials')
    credentials = storage.get()

    http = httplib2.Http()
    http = credentials.authorize(http)

    all_messages = []
    service = discovery.build('gmail', 'v1', http=http)
    first_messages = service.users().messages().list(userId='me').execute()