在数据存储区中为脱机访问存储凭据

时间:2014-01-30 15:50:16

标签: python google-app-engine google-cloud-datastore

我正在使用oauth2decorator_from_clientsecrets()来查询各种Google API。我必须存储凭据,以便我可以离线访问用户的数据(在cron作业中)。我有以下凭据类设置:

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

我尝试将凭据存储在数据存储区中,如下所示:

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

我收到以下错误:

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

当我查看documentation时,看起来装饰者应该有get_credentials()。

我正在采取这种正确的方式吗?

1 个答案:

答案 0 :(得分:0)

使用示例:

以下代码需要额外的导入:

from google.appengine.api import users
from google.appengine.api import memcache
import pickle

触发流程示例:

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)

保存

...

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)

获取

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