How to do OAuth-requiring operations in a GAE Task Queue?

邮差的信 提交于 2019-11-30 10:32:21

Since the Task Queue task will be spawned by your application, none of the headers from your original request will be sent through. In particular, the Cookies header identifying your user via the SACSID cookie for your application (provided by the App Engine Users API).

UPDATE: (This was added after the original post.) As a result of no cookies, the SACSID cookie identifying the user won't be there, hence the decorator.oauth_required designation will force a redirect (which is HTTP 302) EVERY time the cron job runs.

Instead of trying to get the current user from the decorator, you are better off passing along the App Engine User ID to your task. First get the current user (within your decorated method):

from google.appengine.api import users
# Guaranteed not to be None by the decorator
current_user = users.get_current_user()

and then pass along the App Engine User ID in the task

import urllib
query_string = urllib.urlencode({'user_id': current_user.user_id()})
taskqueue.add(url='/updateworker?' + query_string)

Then within your task, you can retrieve grab that user_id

# This is the 'user_id' you appended in the query string
user_id = self.request.get('user_id')

and use it to get that user's credentials as is done in the decorator:

from oauth2client.appengine import CredentialsModel
from oauth2client.appengine import StorageByKeyName
# This assumes you are using the defaults for OAuth2Decorator,
# which your above code is
credentials = StorageByKeyName(
    CredentialsModel, user_id, 'credentials').get()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!