如何使用 Google 驱动器 API 和 Python 覆盖文件?

How to overwrite a file using Google Drive API with Python?

我想创建一个简单的脚本,使用 cronjob 每 5 分钟将一个文件上传到我的云端硬盘。这是我到目前为止使用从不同位置(主要是 2:getting started 页面和 create 页面)提取的样板代码的代码:

from __future__ import print_function
from apiclient import errors
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 googleapiclient.http import MediaFileUpload

def activateService():
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    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(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    return build('drive', 'v3', credentials=creds)

SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly',
          'https://www.googleapis.com/auth/drive.file']

myservice = activateService()

file_metadata = {'name': 'myFile.txt'}
media = MediaFileUpload("myFile.txt", mimetype="text/plain")
file = myservice.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()

上面的代码在“根”位置成功创建了文件,但现在我如何才能让它覆盖以前创建的文件而不是每次都创建新版本?我想我需要使用 update API 调用 (https://developers.google.com/drive/api/v3/reference/files/update) 但此文档页面上没有示例代码,这让我遇到了障碍。任何试图破译 API 页面以创建 Python 代码的帮助将不胜感激,谢谢!

您的代码每次都会创建一个新文件。

myservice.files().create

您需要使用File update

唯一的区别是您需要传递文件 ID。

file = service.files().update(fileId=file_id, media_body=media_body).execute()