I’m working on a Python script to automatically fetch files from Google Drive using their API. I got the basic authentication working fine following the official guide, but now I’m stuck on the actual file download part.
Here’s my current code that’s giving me trouble:
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from oauth2client import file, client, tools
from httplib2 import Http
import io
API_SCOPE = 'https://www.googleapis.com/auth/drive.readonly'
def download_file():
token_store = file.Storage('my_token.json')
credentials = token_store.get()
if not credentials or credentials.invalid:
auth_flow = client.flow_from_clientsecrets('client_secrets.json', API_SCOPE)
credentials = tools.run_flow(auth_flow, token_store)
drive_api = build('drive', 'v3', http=credentials.authorize(Http()))
target_file_id = 'my_document_id_here'
download_request = drive_api.files().get_media(fileId=target_file_id)
buffer = io.BytesIO()
media_downloader = MediaIoBaseDownload(buffer, download_request)
completed = False
while not completed:
progress, completed = media_downloader.next_chunk()
print(f"Downloaded {int(progress.progress() * 100)}%")
with open('saved_file.pdf', 'wb') as output_file:
output_file.write(buffer.getvalue())
if __name__ == '__main__':
download_file()
The error I keep getting is about MediaIoBaseDownload not being recognized. I tried different approaches but nothing seems to work. What am I missing here? Any help would be great because I’ve been stuck on this for hours.