用Python将文件上传到带有其API的Google驱动器时出现问题

时间:2019-05-13 14:58:02

标签: python google-drive-api

我正尝试使用其Python API将文件上传到Google云端硬盘,因为如果用户互动,我需要编写一个脚本来将服务器的自动备份副本上传到Google云端硬盘。我有以下代码是从Google云端硬盘文档中提取的。

我的脚本代码:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient.http import MediaFileUpload

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    results = service.files().list(
        pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

file_metadata = {
  'name' : 'report.csv',
  'mimeType' : 'application/vnd.google-apps.spreadsheet'
}
media = MediaFileUpload('files/report.csv',
                        mimetype='text/csv',
                        resumable=True)
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print ("File ID: %s" % file.get("id"))
main()

显示给我的错误是这些:

Traceback (most recent call last):
  File "gdriveprueba.py", line 55, in <module>
    resumable=True)
  File "/home/servicioweb/.local/lib/python2.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/servicioweb/.local/lib/python2.7/site-packages/googleapiclient/http.py", line 554, in __init__
    fd = open(self._filename, 'rb')
IOError: [Errno 2] No such file or directory: 'files/report.csv'

文件目录是在Google云端硬盘中手动创建的,但它不断告诉我找不到文件,看不见的是什么情况?我有2天的时间,无法从脚本上载文件。

1 个答案:

答案 0 :(得分:0)

您正在混淆第50行和第53行的参数。 name结构中的参数file_metadata指的是Google驱动器上文件的名称MediaFileUpload构造函数的第一个参数引用本地驱动器上的路径。为了使代码正常工作,该文件必须存在。另外,您在行drive_service上引用了一个未定义的变量56。您可以将在主函数中定义的变量service重新定义为global variable,也可以将请求api上传的代码(从行49开始)移到函数中main。另外,在上传代码实际创建服务对象之前,首先需要调用main

如果仅要将其上传到驱动器的根目录,则可以仅创建相对于该文件的文件files/report.csv,然后在文件根目录下创建文件report.csv。您的驱动器。

要创建文件files/report.csv,您需要在Google驱动器上找到目录fileId的{​​{1}},并将其作为参数发送到files api打电话。

要找到create,请运行以下代码:

fileId

现在在api请求中使用变量dirp = "files" # Name of directory to find. parent_id = "" # The id we are looking for. query = ("name='%s'" % (dirp)) resp = service.files().list( q=query, fields="files(id, name)", pageToken=None).execute() files = resp.get('files', []) if len(files) > 0: parent_id = files[0].get('id') 创建文件。

parent_id

Here是有关media = MediaFileUpload('report.csv', mimetype='text/csv', resumable=True) meta_data= { 'name': 'report.csv', 'mimeType' : 'application/vnd.google-apps.spreadsheet', 'parents': [parent_id] } f = service.files().create( body=meta_data, media_body=media, fields='id').execute() if not f is None: print("[*] uploaded %s" % (f.get('id'))) 函数参数的更多信息。

工作代码如下:

create