要从Google API获取访问令牌(access token),你需要遵循以下步骤:
google-api-python-client
库。通过运行以下命令安装:pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
from google_auth_oauthlib.flow import InstalledAppFlow
from google.oauth2.credentials import Credentials
# 替换为你的凭据文件路径
SCOPES = ['https://www.googleapis.com/auth/calendar']
def get_access_token():
flow = InstalledAppFlow.from_client_secrets_file('path/to/your/credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# 保存凭据以便后续使用
with open('token.pickle', 'wb') as token:
token.write(creds.to_json().encode('utf-8'))
return creds
if __name__ == '__main__':
get_access_token()
运行上述代码,将会打开浏览器窗口要求你授权你的应用。同意授权后,代码将获取并保存访问令牌。以后,你可以直接从token.pickle
文件中加载访问令牌,而不需要再次进行授权流程。
领取专属 10元无门槛券
手把手带您无忧上云