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)
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()
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
*
Returns all information
Pass the required items separated by commas
self.service.files().get(fileId=FILE_ID, fields="*").execute()
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',
)
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