问题描述
我曾尝试使用Python脚本从本地系统将文件上传到Google云端硬盘,但始终收到HttpError403.脚本如下:
I have tried uploading file to Google Drive from my local system using a Python script but I keep getting HttpError 403. The script is as follows:
from googleapiclient.http import MediaFileUpload
from googleapiclient import discovery
import httplib2
import auth
SCOPES = "https://www.googleapis.com/auth/drive"
CLIENT_SECRET_FILE = "client_secret.json"
APPLICATION_NAME = "test"
authInst = auth.auth(SCOPES, CLIENT_SECRET_FILE, APPLICATION_NAME)
credentials = authInst.getCredentials()
http = credentials.authorize(httplib2.Http())
drive_serivce = discovery.build('drive', 'v3', credentials=credentials)
file_metadata = {'name': 'gb1.png'}
media = MediaFileUpload('./gb.png',
mimetype='image/png')
file = drive_serivce.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print('File ID: %s' % file.get('id'))
错误是:
googleapiclient.errors.HttpError: <HttpError 403 when requesting
https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&alt=json&fields=id
returned "Insufficient Permission: Request had insufficient authentication scopes.">
我在代码中使用了正确的范围还是遗漏了什么?
Am I using the right scope in the code or missing anything ?
我还尝试了在网上找到的脚本,它可以正常工作,但问题是它需要一个静态令牌,该令牌会在一段时间后过期.那么如何动态刷新令牌?
I also tried a script I found online and it is working fine but the issue is that it takes a static token, which expires after some time. So how can I refresh the token dynamically?
这是我的代码:
import json
import requests
headers = {
"Authorization": "Bearer TOKEN"}
para = {
"name": "account.csv",
"parents": ["FOLDER_ID"]
}
files = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': ('mimeType', open("./test.csv", "rb"))
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(r.text)
推荐答案
要使用范围'https://www.googleapis.com/auth/drive',您需要提交Google应用进行验证.
To use the scope 'https://www.googleapis.com/auth/drive' you need to submit the google app for verification.
因此,请使用范围'https://www.googleapis.com/auth/drive.file'代替'https://www.googleapis.com/auth/drive 以上传未经验证的文件.
So use the scope 'https://www.googleapis.com/auth/drive.file' instead of 'https://www.googleapis.com/auth/drive' to upload files without verification.
也将SCOPES用作列表.
Also use SCOPES as list.
例如:SCOPES = ['https://www.googleapis.com/auth/drive.file']
我可以使用上述SCOPE成功地将文件上传并下载到google驱动器中.
I can successfully upload and download the files to google drive by using the above SCOPE.
这篇关于如何使用Python和Drive API v3将文件上传到Google Drive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!