【发布时间】: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