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

后端 未结 1 1832
独厮守ぢ
独厮守ぢ 2021-01-01 07:00

I have a simple Google App Engine app that includes a /update page which updates a YouTube playlist. It looks like this:

class UpdatePage(webapp         


        
1条回答
  •  时光说笑
    2021-01-01 07:34

    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()
    

    0 讨论(0)
提交回复
热议问题