Alex Alex - 2 months ago 17
Python Question

Storing Credentials for Offline Access in Datastore

I am using the

oauth2decorator_from_clientsecrets()
to query various Google API's. I have to store the credentials so I can access the user's data offline (in a cron job). I have the following Credentials class Set up:

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


I try to store the credentials in the Datastore as follows:

if decorator.has_credentials():
storage = StorageByKeyName(CredentialsModel, user.user_id(),'credentials')
credentials = decorator.get_credentials()
storage.put(credentials)


I receive the following error:

AttributeError: 'OAuth2DecoratorFromClientSecrets' object has no attribute 'get_credentials'


When I looked at the documentation it looks like the decorator should have get_credentials().

I am going about this correct way?

Answer

Example of usage:

Trigger flow example:

flow = OAuth2WebServerFlow(
            client_id=client_id,
            client_secret=client_secret,
            scope=scope,

            access_type = 'offline',
            approval_prompt='force',
            redirect_uri=self.request.relative_url('/admin/auth_return'))
# Get the url now
authorize_url = flow.step1_get_authorize_url()
# Save flow object in memcache for later retrieval on OAuth callback,
# and redirect this session to Google's OAuth 2.0 authorization site.
logging.info('saving flow for user ' + user.user_id())
memcache.set(user.user_id(), pickle.dumps(flow))
# redirect directly
self.redirect(authorize_url, abort=True)

Save

...

user = users.get_current_user()
logging.info('retrieving flow for user ' + user.user_id())
flow = pickle.loads(memcache.get(user.user_id()))

credentials = flow.step2_exchange(self.request.params)
StorageByKeyName(CredentialsModel, user.user_id(), 'credentials').locked_put(credentials)

Get

# here is how you can get them
credentials = StorageByKeyName(CredentialsModel, user.user_id(),'credentials').locked_get()
...
Comments