无法运行谷歌云"ValueError: Authorized user info was not..."



我正在尝试为Google Drive Python API运行quickstart.py,但我得到了以下错误:

Traceback (most recent call last):
raise ValueError(
ValueError: Authorized user info was not in the expected format, missing fields client_id, client_secret, refresh_token.
Process finished with exit code 1

代码:

from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
def main():
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.json 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.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
if __name__ == '__main__':
main()

xx.json文件编辑为以下格式:

{
"project_id":"xxxxxxxxxxxx",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://oauth2.googleapis.com/token", 
"client_id":"xxxxxxxxxxxxx",
"client_secret":"xxxxxxxxxxxx",
"auth_provider_x509_cert_url":"xxxxxxxxxxx",
"redirect_uris":["xxxxxxxxxxxxxxxx","xxxxxxxxxx"]
}

我遇到了同样的问题。我所做的是使用服务帐户,这样我的脚本就可以访问驱动器。

from google.oauth2.service_account import Credentials
credentials = Credentials.from_service_account_file(
filename=service_account_file_path,
scopes=SCOPES
)
drive = build('drive', 'v3', credentials=credentials)
results = drive.files().list().execute()
files = results.get('files', [])

如果有人来这里寻找答案,请注意,在这个问题上发布了有效的答案。

简而言之,不要下载凭据文件并将其重命名为token.json。只需在目录中没有任何令牌文件的情况下运行脚本。在第一次运行时,当代码找不到有效的令牌文件时,它会启动浏览器并将您带到授权页面。在授予访问权限时,会为您创建令牌文件。

相关内容

最新更新