使用 Python 清空 Google 驱动器垃圾箱

Empty Google Drive Trash with Python

我正在尝试用 API 清空我的 google 驱动器垃圾箱,但没有成功。我试过使用请求库,脚本运行没有错误,但驱动器垃圾没有被删除。我已经能够通过 API 获取文件,但无法删除或清空垃圾箱。似乎我应该能够发送一个 http 请求,但事实证明这对我来说比看起来要困难得多。任何建议将不胜感激。这是我所拥有的。我什至没有收到 json 回复。

from __future__ import print_function
import httplib2
import os
import requests

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage


try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'C:\Scripts\Link Expiration\client_secret.json'
APPLICATION_NAME = 'Drive API Delete Trash'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v2', http=http)

    r = requests.delete('https://www.googleapis.com/drive/v2/files/trash')
    r.json()

if __name__ == '__main__':
    main()

这个修改怎么样?

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v2', http=http) # you can also use at 'v3'.

    service.files().emptyTrash().execute() # Added

如果我误解了你的问题,我很抱歉。

这不是 python,但这是一种通过 api 调用清空垃圾箱的简单方法。 Google Empty Trash API