我正在尝试在我的 Colab 笔记本上使用 google API。我正在关注this,但它似乎已经过时了。
我最终关注了 this 以了解如何制作我的 OAuth 2.0 客户端 ID
但是当我运行代码并单击链接时出现此错误: 您无法登录,因为此应用发送了无效请求。您可以稍后重试,或联系开发者解决此问题
这是我的代码:
!pip install httpx
!pip install starlette
!pip install fastapi
from typing import Optional
import os
from starlette.requests import Request
from fastapi import FastAPI
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 get_authenticated_service():
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
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('/content/client_secret_99.apps.googleusercontent.com.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
service = build('drive', 'v3', credentials=creds)
return service
except HttpError as error:
print(f"An error occurred: {error}")
return None
def list_drive_files(service, orderBy='modifiedByMeTime desc', pageSize=5):
results = service.files().list(
pageSize=pageSize, orderBy=orderBy, fields="nextPageToken, files(id, name, mimeType)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(f"{item['name']} ({item['mimeType']})")
if __name__ == '__main__':
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
service = get_authenticated_service()
list_drive_files(service, orderBy='modifiedByMeTime desc', pageSize=5)
所以我错过了什么?