如何使用Python生成长期有效的Picasa令牌(或一般的Google oAuth 2.0启用服务)?

2024-05-23 14:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

不得不说,我不太清楚如何在picasaapiversion2中使用oauth2.0。从Google文档本身(cmiw),我得到的印象是picasaapi版本1已被弃用,这意味着Picasa的pythongdata(只支持版本1)根本没有用。在

因此,我使用基本的Picasa documentation开发自己的类。但是,我发现生成的令牌非常短暂:用户需要重新验证他/她自己。我们可以让用户只重新验证一个令牌吗?如果令牌过期了,它会自动刷新吗?在

这是我为解决Picasa问题而开发的oAuth类。很乐意就如何修复这个类以允许长期生存的令牌提供建议

class OAuth():
"""
Simplify oauth process
"""
def __init__(self, **kwargs):
    self.client_secret_file = kwargs.get('client_secret_file')
    self.token_location = os.path.join(kwargs.get('token_location'), kwargs.get('token_filename'))
    self.scope = kwargs.get('scope')
    self.credentials = None

def is_authenticated(self):
    storage = Storage(self.token_location)
    self.credentials = storage.get()
    authenticated = self.credentials is not None and not self.credentials.invalid
    Logger.debug('oAuth: authenticated = %s' % authenticated)
    return authenticated

def authenticate(self):
    if self.scope is None:
        Logger.error('oauth: please specify scope')
        return

    missing_message = '''
    WARNING: Please configure OAuth 2.0
    To make this code run you will need to populate the client_secrets.json file
    found at: %s
    with information from the Developers Console
    https://console.developers.google.com/
    For more information about the client_secrets.json file format, please visit:
    https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
    ''' % self.client_secret_file

    flow = flow_from_clientsecrets(self.client_secret_file,
                                   message=missing_message,
                                   scope=self.scope)

    # ca_certs_file = os.path.join('cacert.pem')
    flags = argparser.parse_args()
    storage = Storage(self.token_location)
    self.credentials = run_flow(flow, storage, flags)#, http=httplib2.Http(ca_certs=ca_certs_file))

编辑时间: 我在这里加上我的解决方案。在

^{pr2}$

Tags: selfclienttokengetsecretdefstoragelocation
2条回答

令牌有两种类型:访问令牌和刷新令牌。当用户第一次授予您访问权限时,您的应用程序应该同时收到这两个消息。在

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
  "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

保存刷新令牌以供将来使用很重要。当第一个访问令牌过期时,您必须使用刷新令牌来获取新令牌。在

https://developers.google.com/accounts/docs/OAuth2WebServer#refresh

同时考虑使用https://github.com/google/oauth2client

相关问题 更多 >