Google Drive Api Tips (Python)

Initialization for service account

https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=ja Get the json file referring to here

from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/drive']

credentials = service_account.Credentials.from_service_account_file(JSON_FILE_PATH, scopes=SCOPE)
self.service = build('drive', 'v3', credentials=credentials)

I want to upload a file to the specified directory

Let's pass the file ID as an array (it is easy to forget)

from apiclient.http import MediaFileUpload

#The file ID of the directory is at the end of the path
# https://drive.google.com/drive/folders/FILE_ID
file_metadata = {'name': 'photo.jpg', 'parents': [FILE_ID]}
media = MediaFileUpload('files/photo.jpg', mimetype='image/jpeg')
file = self.service.files().create(body=file_metadata,
                                   media_body=media,
                                   fields='id').execute()

What should I specify as the mimetype when uploading?

Refer to this area https://developers.google.com/drive/api/v3/mime-types https://developer.mozilla.org/ja/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

I want to see various information about the file

* Returns all information Pass the required items separated by commas

self.service.files().get(fileId=FILE_ID, fields="*").execute()

I uploaded a file but I can't access it

Probably not authorized, let's put it on If you create a directory with authority in advance and upload it to it, you do not need to give authority each time


user_permission = {
        'type': 'user',
        'role': 'writer',
        'domain': '[email protected]'
    }

self.service.permissions().create(
                    fileId=FILE_ID,
                    body=user_permission,
                    fields='id',
                )

Save the downloaded file to the specified path

Let's write with get buffer


import io
from apiclient.http import MediaIoBaseDownload

request = self.service.files().get_media(fileId=FILE_ID)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%." % int(status.progress() * 100))

with open(SAVE_FILE_PATH, "wb") as f:
    f.write(fh.getbuffer())

Recommended Posts

Google Drive Api Tips (Python)
python tips
Upload JPG file using Google Drive API in Python
python tips
Python Tips
Python tips
[Python] Hit the Google Translation API
[Python3] Google translate google translate without using api
Download Google Drive files in Python
Use Google Analytics API from Python
Python: Extract file information from shared drive with Google Drive API
Python Conda Tips
Python debugging tips
Python click tips
Get Google Fit API data in Python
Unexpectedly (?) Python tips
Use Google Cloud Vision API from Python
Regularly upload files to Google Drive using the Google Drive API in Python
Creating Google Spreadsheet using Python / Google Data API
Upload images to Google Drive with Python
Run Google Analytics API (core v3) in python
Tweet (API 1.1) on Google App Engine for Python
Tips for hitting the ATND API in Python
Upload files to Google Drive with Lambda (Python)
Python and numpy tips
Google Drive file move
Google Colab Tips Organize
Drive WebDriver with python
Evernote API in Python
Python Tips (my memo)
OpenCV3 Python API list
Python PyTorch install tips
C API in Python 3
TensorFlow API memo (Python)
[Blender x Python] Blender Python tips (11/100)
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
Google Drive API Set File Permission (Set permissions on Google Drive files)
Make a copy of a Google Drive file from Python
[Python] Get insight data using Google My Business API
Speech transcription procedure using Python and Google Cloud Speech API
Speech file recognition by Google Speech API v2 using Python
Upload to a shared drive with Google Drive API V3
Hit Mastodon's API in Python
Use Trello API with python
Python / Numpy np.newaxis thinking tips
ls -R on Google Drive
AWS CDK-Lambda + API Gateway (Python)
EXE Web API by Python
Use Twitter API with Python
Study Python with Google Colaboratory
Receiving standard input tips @ python
[Tips] Handle Athena with Python
Web API with Python + Falcon
Play RocketChat with API / Python
Get data from analytics API with Google API Client for python
Blender Python API in Houdini (Python 3)
Call the API with python3.
Mount google drive with google-drive-ocamlfuse
Use subsonic API with python3
[Python + Selenium] Tips for scraping
~ Tips for beginners to Python ③ ~