Empty Google Drive Trash with Python

折月煮酒 提交于 2020-01-04 14:07:04

问题


I am trying to empty my google drive trash bin with the API, but with no luck. I have tried using the requests library, and the script runs through without errors, but the drive trash is not deleted. I have been able to get files via the API, but not delete or empty the trash. Seems I should be able to just send an http request, but this is proving far more difficult for me than it seems it should be. Any advice would be greatly appreciated. Here is what I have. I am not even getting a json response.

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()

回答1:


How about this modification?

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

If I misunderstand your question, I'm sorry.



来源:https://stackoverflow.com/questions/48820510/empty-google-drive-trash-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!