1

I'm trying to use requests in python with the google drive api v3. I can get my script to authenticate and run calls with a service. But I notice that most of the documentation for API V3 shows examples using http requests under the "reference" tab. When I try to complete a call using requests, I'm not sure how to put my Oath 2.0 authentication in to reference the token.pickle. Tried to force the token to a string but did not work. The whole script is below. You can see the "#delete mp4File" section is where I'm trying to create a request and add authentication. This is where I need help.

    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
import os
import io
from googleapiclient.http import MediaIoBaseDownload
import requests

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

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(
                'client_secrets.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

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

    # List contents of mp4 folder
    results = service.files().list(
        q="'XXXXXXXXXXXXXXXXXXXX' in parents", pageSize=1).execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        for item in items:
            mp4File=(u'{0}'.format(item['id']))
            mp4Name=(u'{0}'.format(item['name']))
            print (mp4Name + " " + mp4File)

    # Download mp4File
    file_id = mp4File
    request = service.files().get_media(fileId=file_id)
    fh = io.FileIO(mp4Name, 'wb')
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()

    #delete mp4File
    url = "https://www.googleapis.com/drive/v3/files/" + file_id

    headers = {
                'Authorization': 'Bearer ' + str(token)
                }

    response = requests.request("DELETE", url, headers=headers)

    print(response.text.encode('utf8'))



if __name__ == '__main__':
    main()

6
  • I have to apologize for my poor English skill. I cannot understand about When I try to complete a call using requests, I'm not sure how to put my Oath 2.0 authentication in to reference the token.pickle.. Can I ask you about the detail of your current issue and your goal? For example, is Quickstart for python useful? Commented Sep 2, 2020 at 0:03
  • @Tanaike Yes! I'd be happy to expand on this in detail. I created a project and gave it the scopes to download, delete and edit files on gdrive. I grabbed the authentication code from the quickstart to get a token. I used to token for a couple of previous api calls to list files and download them. Now I want to delete the file that I downloaded. When I look up documentation for this, it just provides an DELETE url http call for drive v3. So I am trying to use requests to execute this call. Does this make sense? Commented Sep 2, 2020 at 3:38
  • Thank you for replying. I have to apologize for my poor English skill again. Unfortunately, from your replying, I couldn't understand about your current issue and your goal. Commented Sep 2, 2020 at 6:24
  • What scope are you using in you application? If it is a read-only scope, then you will need to delete your token.pickle file and reauthenticate, as the quickstart only provides a read-only scope in its example. Commented Sep 2, 2020 at 9:45
  • @RafaGuillermo, I updated my post and included the scopes for you to see. My token.pickle includes these scopes. My basic problem is how to show the token.pickle in a request header to authenticate my call. Tanaike, I updated the wording of my post, let me know if that makes it more clear? Thanks for your help, both of you! Commented Sep 2, 2020 at 16:07

1 Answer 1

2

I believe your goal and your current situation as follows.

  • You want to delete a file in Google Drive using requests with python.
  • Your service = build('drive', 'v3', credentials=creds) can be used for deleting the file.

Modification point:

  • In your script, the access token can be retrieved by creds.token.

When this is reflected to your script, it becomes as follows.

Modified script:

From:
'Authorization': 'Bearer ' + str(token)
To:
'Authorization': 'Bearer ' + creds.token

Other pattern:

When googleapis for python is used like service.files().list(), it becomes as follows.

service.files().delete(fileId=file_id).execute()

Note:

  • The method of "Files: delete" in Drive API returns no values. So please be careful this.

    If successful, this method returns an empty response body.

Reference:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.