【问题标题】:Google drive Python to upload file not working谷歌驱动Python上传文件不起作用
【发布时间】:2020-09-07 16:26:01
【问题描述】:

我正在使用以下代码,正在生成文件 ID,但未上传文件。我尝试调试,但它显示与代码输出相同的输出。我已经将服务帐号json文件和test.csv放在了python代码所在的文件夹中。

from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload




def uploadGdrive():
    SCOPES = ['https://www.googleapis.com/auth/drive.file']
    SERVICE_ACCOUNT_FILE = './iron-tea-266706-8a1f9ee69710.json'
    folder_id = '15xc7s-dFnpW6pjtjtUH4kT1BnZ46ffFh'
    #file_id = '1IcbtXGW1ZMmv64SqqXJZCsFrwMlE3NiQcDZR98XuFX8'
    file_location='./test.csv'

    creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    service = build('drive', 'v3', credentials=creds)
    file_metadata = {
        'name': 'Master Summary',
        'mimeType': 'application/vnd.google-apps.spreadsheet'
    }

    media = MediaFileUpload(
        '{}'.format(file_location),
        mimetype='text/csv',
        resumable=True)

    #This is to update existing file
    #file = service.files().update(body=file_metadata,media_body=media,fileId='{}'.format(file_id)).execute()
    #print(file.get('id'))

    #this is to create new  file
    file = service.files().create(body=file_metadata,
                                   media_body=media,
                                   fields='id').execute()
    print('File ID: %s' % file.get('id'))

if __name__ == '__main__':
    uploadGdrive()

【问题讨论】:

  • 这个帖子能解决你的问题吗? stackoverflow.com/q/63545788
  • 文件上传正常,但文件正在上传到您服务帐户的驱动器,而不是您自己的驱动器。为避免这种情况,您需要使用模拟。
  • 您的意思是说服务帐户无权访问我的帐户。我提到了“父母”:file_metadata 下的 [folder_id],现在它失败了,找不到文件夹 ID
  • 没错,服务帐号默认无权访问您的帐号。与服务帐户共享文件夹,或使用domain-wide delegation

标签: python google-api google-drive-api google-api-python-client service-accounts


【解决方案1】:

服务帐户不是您。服务帐户是一个虚拟用户,它有自己的驱动器帐户。它上传的文件归它所有。

您的文件可能正在上传到服务帐户驱动器帐户。或者在任何地方 '15xc7s-dFnpW6pjtjtUH4kT1BnZ46ffFh' 假设服务帐户有权写入该目录。您可以通过执行 file.list 并查看它当前可以访问哪些文件来看到这一点。

如果要创建的文件成功,它将返回一个 file.id 作为响应的一部分,您也可以检查它。

您可以在自己的 google drive 帐户上创建一个目录,与服务帐户共享该目录。然后让服务帐户将文件上传到该目录,然后您就可以在自己的帐户上看到它们。您还需要在上传文件时授予自己对文件的权限。查看 permissions.create。

或者,您可以让服务帐户将文件上传到自己的帐户,然后为您添加文件的权限,以便您能够看到它。查看 permissions.create。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2018-07-28
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多