Search code examples
pythonpython-3.xgoogle-drive-apigoogle-api-clientgoogle-api-python-client

Downloading files from Google Drive with Python


I´m coding with Python, to make a program which download files using Googl Drive API. This is the code:

import os
import io
from googleapiclient.discovery import build
from googleapiclient.http import MediaIOBaseDownload

CLIENT_SECRET_FILE = 'client_secret.json'
API_NAME = 'drive'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/drive']

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(
                'credentials.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)



    file_ids = ['1aKiVaINA2-_o8zttzYiH60jShzFQRUny', '1Xyy9-LWwTtnWZ1HLVJ74XT0PVsoixHOi']
    file_names = ['PicsArt_08-02-06.15.34.jpg', 'PicsArt_07-22-04.49.32.jpg']
    for file_id, file_name in zip(file_ids, file_names):
        request = service.files().get_media(fileId=file_id)

        fh = io.BytesIO()
        downloader = MediaIOBaseDownload(fd=fh, request=request)

        done = False

        while not done:
            status, done = downloader.next_chunk()
            print('Download progress {0}'.format(status.progress( * 100)))
    
        fh.seek(0)
        with open(os.path.join('./Random Files', file_name), 'wb') as f:
            f.write(fh.read())
            f.close()

if __name__ == '__main__':
    main()

When I run the program I´m getting this error:

Traceback (most recent call last): File "download.py", line 4, in from googleapiclient.http import MediaIOBaseDownload ImportError: cannot import name 'MediaIOBaseDownload' from 'googleapiclient.http' (C:\Users\Usuario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\googleapiclient\http.py)

Any solution?


Solution

  • I get that your goal is to import the class http.MediaIoBaseDownload from the Python googleapiclient package. If I got it correctly, then you are very close to reaching your goal. You should change the problematic line with this one:

    from googleapiclient.http import MediaIoBaseDownload
    

    Please, notice how MediaIoBaseDownload is spelled differently. Ask me any question if you still have doubts.