如何使用Python和驱动器API v3将文件上载到Google驱动器

2024-04-20 14:04:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾尝试使用Python脚本将文件从本地系统上传到Google Drive,但我一直收到HttpError 403。脚本如下:

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)

Tags: httpsimport脚本comauthjsonwwwv3
3条回答

您可以使用google-api-python-client构建驱动器服务,以使用Drive API

  • 按照this answer的前10个步骤获得授权
  • 如果您希望用户只通过一次同意屏幕,那么store将凭证保存在文件中它们包括一个刷新令牌,应用程序可以使用该令牌在过期后请求授权

使用有效的驱动器服务可以通过调用以下函数upload_file上传文件:

def upload_file(drive_service, filename, mimetype, upload_filename, resumable=True, chunksize=262144):
    media = MediaFileUpload(filename, mimetype=mimetype, resumable=resumable, chunksize=chunksize)
    # Add all the writable properties you want the file to have in the body!
    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!")

现在传入参数并调用函数

# Upload file
upload_file(drive_service, 'my_local_image.png', 'image/png', 'my_imageination.png' )

您将在Google Drive根文件夹中看到名为:my_imagination.png的文件

有关驱动器API v3服务和可用方法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

上传到驱动器中的特定文件夹很容易…

只需在请求主体中添加父文件夹Id即可

这是properties of a Fileparents[] property of File

示例:

request_body = {
  "name": "getting_creative_now.png",
  "parents": ['myFiRsTPaRentFolderId',
              'MyOtherParentId',
              'IcanTgetEnoughParentsId'],
}

回答:

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

更多信息:

只要您拥有正确的凭据集,那么在更新应用程序的作用域时所需的全部工作就是重新获取令牌。删除位于应用程序根文件夹中的令牌文件,然后再次运行应用程序。如果您在开发人员控制台中启用了https://www.googleapis.com/auth/drive范围、Gmail API,那么您应该很好

参考文献:

"Insufficient Permission: Request had insufficient authentication scopes."

表示与您进行身份验证的用户未授予您的应用程序执行您尝试执行的操作的权限

files.create方法要求您已使用以下作用域之一对用户进行了身份验证

enter image description here

而您的代码似乎正在使用完整的驱动器作用域。我怀疑发生的情况是,您对用户进行了身份验证,然后更改了代码中的作用域,而没有促使用户再次登录并授予同意。你需要从你的应用程序中删除用户同意,或者让他们直接在他们的谷歌帐户中删除,或者只是删除你在应用程序中存储的凭据。这将强制用户再次登录

google登录还有一个approval prompt force选项,但我不是python开发人员,所以我不确定如何强制。它应该类似于下面的提示class='approve'行

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')

同意屏幕

如果操作正确,用户将看到如下屏幕

enter image description here

提示他们授予您对其驱动器帐户的完全访问权限

代币泡菜

如果您在这里学习Google教程https://developers.google.com/drive/api/v3/quickstart/python,则需要删除包含用户存储同意的token.pickle

if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)

相关问题 更多 >