1

I have the access token and file id of the file I need to download. After authenticating the user in a react application and using File picker API, I got both of them. I need to pass them a python file that can download the file but without user intervention(without user permission )

Any suggestion on how to do it? I do not have a shareable link. I have the file id and the access token after authentication. I need to download it through another application written in python. Answers on stack overflow to download drive file using python have to do authentication using OAuth first, but in my case, I need to download the file without authentication

Knight
  • 39
  • 2
  • 2
    I closed as a duplicate based on the information in the currently only answer, but you might want to try to [edit] to clarify that this is different somehow, and should be reopened as a distinct question. The Docker mention in the title seems spurious, and isn't reflected in the question itself, but might be something you could elaborate on if it creates new challenges which are not solved by the duplicate. – tripleee May 29 '22 at 11:07

1 Answers1

0

If by "drive's url" you mean the shareable link of a file on Google Drive, then the following might help:

import requests

def download_file_from_google_drive(id, destination):
    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)    

def get_confirm_token(response):
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            return value

    return None

def save_response_content(response, destination):
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

if __name__ == "__main__":
    file_id = 'TAKE ID FROM SHAREABLE LINK'
    destination = 'DESTINATION FILE ON YOUR DISK'
    download_file_from_google_drive(file_id, destination)

The snipped does not use pydrive, nor the Google Drive SDK, though. It uses the requests module (which is, somehow, an alternative to urllib2).

When downloading large files from Google Drive, a single GET request is not sufficient. A second one is needed - see wget/curl large file from google drive.

Originally answered here

Bipul Jaishwal
  • 259
  • 2
  • 14