使用Python编写flow_from_clientsecrets()授权流程的工具函数
发布时间:2023-12-11 15:50:33
flow_from_clientsecrets()是Google提供的用于OAuth2授权流程的工具函数,可以方便地进行用户授权和获取访问令牌的操作。使用Python编写的工具函数如下:
from google_auth_oauthlib.flow import Flow
from google.oauth2.credentials import Credentials
import os
def authorize_scopes(client_secrets_file, scopes, token_file):
"""
使用flow_from_clientsecrets()进行授权流程
:param client_secrets_file: 客户端凭据文件的路径
:param scopes: 需要授权的作用域列表
:param token_file: 保存访问令牌的文件路径
:return: 授权后的凭据对象
"""
flow = Flow.from_client_secrets_file(client_secrets_file, scopes)
flow.redirect_uri = 'http://localhost:8080/oauth2callback'
# 如果已经有保存的访问令牌文件,则直接读取
if os.path.exists(token_file):
creds = Credentials.from_authorized_user_file(token_file, scopes)
# 判断凭据是否过期,如果没有则返回
if not creds.expired and creds.valid:
return creds
# 如果凭据过期,则自动刷新
try:
creds.refresh(flow)
return creds
except:
print('凭据刷新失败,请重新授权')
# 如果没有保存的访问令牌文件,则进行用户授权
authorization_url, state = flow.authorization_url(access_type='offline')
print('请访问以下链接并授权:
{}'.format(authorization_url))
code = input('请输入授权码:')
try:
flow.fetch_token(code=code)
creds = flow.credentials
# 保存访问令牌到文件
with open(token_file, 'w') as token:
token.write(creds.to_json())
return creds
except:
print('授权失败,请重试')
使用示例:
if __name__ == '__main__':
# 客户端凭据文件
client_secrets_file = 'client_secrets.json'
# 需要授权的作用域列表
scopes = ['https://www.googleapis.com/auth/drive']
# 保存访问令牌的文件路径
token_file = 'token.json'
creds = authorize_scopes(client_secrets_file, scopes, token_file)
# 使用凭据对象进行API调用
if creds:
# do something
在上面的示例中,首先在if __name__ == '__main__':的代码块中定义了需要授权的作用域列表scopes,以及客户端凭据文件client_secrets_file和保存访问令牌的文件路径token_file。
然后调用authorize_scopes()函数,传入这些参数,进行授权流程。如果之前已经保存了访问令牌,则直接读取,并进行过期判断,如果没有过期则返回凭据对象。如果凭据过期,则自动刷新凭据。
如果没有保存的访问令牌文件,则进行用户授权,获取授权码,然后使用授权码获取访问令牌。最后将访问令牌保存到文件,并返回凭据对象。
最后,在获得凭据对象之后,可以使用它进行相应的API调用。
