如何使用Python和Drive API v3将文件上传到Google云端硬盘

问题描述 投票:0回答:3

我尝试使用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)

任何帮助都会感激。

python google-api google-drive-api google-oauth google-api-python-client
3个回答
0
投票

删除您的token.pickle文件并重新运行您的应用程序。

更多信息:只要您具有正确的凭据集,那么更新应用程序范围时所需要的就是重新获得令牌。删除位于应用程序根文件夹中的令牌文件,然后再次运行该应用程序。如果您具有https://www.googleapis.com/auth/drive范围,并且在开发人员控制台中启用了

Gmail API,则应该不错。

参考:

Google Drive API - Files: create method


0
投票
那么如何构建与Drive API交互的服务?

按照feel free to contribute的前10个步骤获得授权。
  • [如果您只希望用户通过同意屏幕一次,然后将凭据存储在文件中,因为它们包含刷新令牌,您可以在过期后再次使用获取有效凭据,因此您可以将凭据this answer转换为文件。但是如何? pickle
    我现在拥有有效的云端硬盘服务,如何上传文件?

  • 例如,编写类似于以下Sample here函数的函数:

    upload_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()

    我相信这会回答您的问题,如果我误解了一些东西,请解释一下。

  • 0
    投票
    “权限不足:请求的身份验证范围不足。”
    意味着您已通过身份验证的用户未授予您的应用程序权限来执行您尝试做的事情。

    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 方法要求您使用以下范围之一对用户进行身份验证。

    files.create

    而您的代码似乎确实在使用完整的驱动器范围。我怀疑发生的事情是您已经对用户进行了身份验证,然后更改了代码中的范围,而没有提升用户再次登录并授予同意。您需要删除用户的同意书,方法是让他们直接在其Google帐户中删除用户同意书,或者仅删除您存储在应用程序中的凭证。这将迫使用户再次登录。

    Google登录名中也有一个批准提示强制选项,但它不是python开发人员,因此无法完全确定如何强制执行。它应该类似于下面的提示符=“同意”行。

    enter image description here

    同意画面

    如果操作正确,用户应该会看到这样的屏幕

    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教程enter image description here,则需要删除包含用户存储的同意的token.pickle。

    https://developers.google.com/drive/api/v3/quickstart/python

    © www.soinside.com 2019 - 2024. All rights reserved.