我尝试使用python脚本从本地系统将文件上传到google驱动器,但我一直收到HttpError403。该脚本如下:
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.">
我在代码中使用了正确的范围还是缺少任何内容?
我还尝试了我在网上找到的脚本,它可以正常工作,但问题是它需要一个静态令牌,该令牌会在一段时间后过期。所以我如何动态刷新令牌?
这是我的代码:
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)
任何帮助都会感激。
token.pickle
文件并重新运行您的应用程序。更多信息:只要您具有正确的凭据集,那么更新应用程序范围时所需要的就是重新获得令牌。删除位于应用程序根文件夹中的令牌文件,然后再次运行该应用程序。如果您具有 和https://www.googleapis.com/auth/drive
范围,并且在开发人员控制台中启用了
Files: create
methodupload_file
def upload_file(drive_service, filename, mimetype, upload_filename, resumable=True, chunksize=262144):
media = MediaFileUpload(filename, mimetype=mimetype, resumable=resumable, chunksize=chunksize)
body = {"name": upload_filename}
request = drive_service.files().create(body=body, media_body=media).execute()
if getFileByteSize(filename) > chunksize:
response = None
while response is None:
chunk = request.next_chunk()
if chunk:
status, response = chunk
if status:
print("Uploaded %d%%." % int(status.progress() * 100))
print("Upload Complete!")
您将在Google云端硬盘根文件夹中看到名称为
my_imageination.png的文件。有关Drive API v3服务和可用方法
# With your built Drive service, your file to upload and your imagination ;) # call the function upload_file upload_file(drive_service, 'my_local_image.png', 'image/png', 'my_imageination.png' )
的更多信息。如果您想知道here功能如何:
getFileSize()
我相信这会回答您的问题,如果我误解了一些东西,请解释一下。
意味着您已通过身份验证的用户未授予您的应用程序权限来执行您尝试做的事情。
def getFileByteSize(filename): # Get file size in python from os import stat file_stats = stat(filename) print('File Size in Bytes is {}'.format(file_stats.st_size)) return file_stats.st_size
方法要求您使用以下范围之一对用户进行身份验证。而您的代码似乎确实在使用完整的驱动器范围。我怀疑发生的事情是您已经对用户进行了身份验证,然后更改了代码中的范围,而没有提升用户再次登录并授予同意。您需要删除用户的同意书,方法是让他们直接在其Google帐户中删除用户同意书,或者仅删除您存储在应用程序中的凭证。这将迫使用户再次登录。
Google登录名中也有一个批准提示强制选项,但它不是python开发人员,因此无法完全确定如何强制执行。它应该类似于下面的提示符=“同意”行。
同意画面
如果操作正确,用户应该会看到这样的屏幕
flow = OAuth2WebServerFlow(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope='https://spreadsheets.google.com/feeds '+ 'https://docs.google.com/feeds', redirect_uri='http://example.com/auth_return', prompt='consent')
提示他们授予您对他们的驱动器帐户的完全访问权限
代币泡菜
[如果您在此处关注Google教程,则需要删除包含用户存储的同意的token.pickle。
https://developers.google.com/drive/api/v3/quickstart/python