我尝试使用python中的OAuth2WebServerFlow获取访问令牌并刷新令牌。但它抛出错误oauth2client.client.FlowExchangeError:invalid_grant格式错误的身份验证代码。
示例代码
from oauth2client.client import OAuth2WebServerFlow
def retrieve_data():
"""
Run through the OAuth flow and retrieve credentials.
Returns a dataset (Users.dataSources.datasets):
https://developers.google.com/fit/rest/v1/reference/users/dataSources/datasets
"""
CLIENT_ID = 'XXXXX'
CLIENT_SECRET = 'XXXX'
OAUTH_SCOPE = ['https://www.googleapis.com/auth/userinfo.email']
REDIRECT_URI = 'XXXXXXX'
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print('Go to the following link in your browser:')
print(authorize_url)
code = input('Enter verification code: ')
print(code)
google_data = flow.step2_exchange(code)
# # http = httplib2.Http()
# # http = google_data.authorize(http)
# print(google_data)
# access_token = google_data.token_response['access_token']
# print(access_token)
retrieve_data()
我也有验证码。我试图在step2_exchange方法中传递代码。它引发此错误('oauth2client.client.FlowExchangeError:invalid_grantMalformed auth code。')如何解决此问题。
按照以下步骤:(1)转到https://console.cloud.google.com/(2)选择您的帐户(3)转到“导航菜单”右上角的汉堡菜单(4)选择API服务,然后选择“凭据”(5)创建凭据并将json文件下载到您的工作目录中(6)还完成oauth客户端屏幕,然后复制并粘贴以下python代码
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.file']
CLIENT_SECRET_FILE = 'e:\\Python Programs\\credentials.json'
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
drive_service = build('drive', 'v3', credentials=creds)
这是通过flow.run_local_server访问令牌的方法