这是尝试过的 我将 O Auth 同意屏幕的状态从测试更改为发布并且应用程序范围是外部的然后我创建了 O Auth 客户端 ID 令牌然后我尝试了这个代码但是当我尝试对应用程序进行身份验证时这会出错。
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/drive']
CLIENT_SECRETS_FILE = 'client.json'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES, redirect_uri=REDIRECT_URI)
auth_url, _ = flow.authorization_url(prompt='consent')
print(f'Please go to this URL to authorize the application: {auth_url}')
auth_code = input('Enter the authorization code: ')
flow.fetch_token(code=auth_code)
creds = flow.credentials
print(f'Access token: {creds.token}')
print(f'Refresh token: {creds.refresh_token}')
你能发现如何在 python 中做到这一点并解决这个错误吗?
你不能使用 urn:ietf:wg:oauth:2.0:oob,这已经停止了。
跟随官方QuickStart
你会好运此示例将使用 creds = flow.run_local_server(port=0) 为您打开同意屏幕,而不是要求您单击一个链接,该链接可能会返回 404 错误,因为您没有运行本地 Web 服务器。
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# 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())
try:
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.')
return
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
except HttpError as error:
# TODO(developer) - Handle errors from drive API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()