我收到以下错误:
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/XXXXXXXXXXXX?alt=media returned "The user has not granted the app 123456789 read access to the file XXXXXXXXXXXX.">
这很奇怪,因为我已经使用OAuth Web身份验证方法进行了身份验证。我也可以列出我的文件。
Google在此处列出了此错误:https://developers.google.com/drive/v3/web/handle-errors#403_the_user_has_not_granted_the_app_appid_verb_access_to_the_file_fileid并建议我提示用户打开该文件。好吧,用户就是我,我打开这个文件大约20次完全没问题。错误不会消失......
以下是我的完整示例:
import os
import httplib2
import io
from oauth2client.file import Storage
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
from googleapiclient.http import MediaIoBaseDownload
location import Location
CLIENT_ID = 'CLIENT ID XYXXYX'
CLIENT_SECRET = 'YYYYYYYYYYYYYYY'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
OUT_PATH = Location.folder_path + "media/dumps/"
CREDS_FILE ='this_file_is_somewhere.json'
storage = Storage(CREDS_FILE)
credentials = storage.get()
if credentials is None:
# Run through the OAuth flow and retrieve credentials
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: ' + authorize_url)
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
storage.put(credentials)
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v3', http=http)
def list_files(service):
page_token = None
while True:
param = {}
if page_token:
param['pageToken'] = page_token
files = service.files().list(**param).execute()
for item in files['items']:
yield item
page_token = files.get('nextPageToken')
if not page_token:
break
def download(file_id, path=OUT_PATH):
request = drive_service.files().get_media(fileId=file_id)
file_meta = drive_service.files().get(fileId=file_id).execute()
name = file_to_get['name']
print(file_meta)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print(int(status.progress() * 100))
f = open(path + '/' + name, 'wb')
f.write(fh.getvalue())
print('File downloaded at', path)
f.close()
download('XXXXXXXXXXXX')
答案 0 :(得分:0)
非常感谢@Tanaike:
只需删除凭证文件并重新创建即可解决该问题。