Why I make this?
I honestly can’t remember. But I think I was trying to upload a file to Google Drive through the API and I couldn’t find a simple code snippet that did just that. So I wrote one.
How to do this?
First, install dependencies listed here: https://developers.google.com/drive/api/v3/quickstart/python#step_1_install_the_google_client_library
Then, follow this code snippet –
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials
from googleapiclient.http import MediaFileUpload
# Set the location of the access token
# Get the token from https://console.cloud.google.com/apis/api/drive.googleapis.com/
ACCESS_TOKEN_LOCATION = "client-secret.json"
# Set the scope of access
# Check the scope for your needs at https://developers.google.com/identity/protocols/oauth2/scopes#drive
SCOPES = ["https://www.googleapis.com/auth/drive"] # This scope is FULL access
# Set authorisation + initialise the service
credentials = Credentials.from_service_account_file(ACCESS_TOKEN_LOCATION, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)
# Set the metadata for the file to be uploaded
file_metadata = {
'name': 'sample.png', # name of the file on Drive
'parents':['thY2Hl25HthY2Hl25H'] # the folder in which to upload; if not specified file is uploaded to root folder on Drive
}
# Set the file location + type of the file to be uploaded
media = MediaFileUpload('./greatphoto.png', mimetype='image/png')
# UPLOAD!
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
# if an ID is returned, the upload was successful
print('File ID: %s' % file.get('id'))
|
Note:
- Set
fields='*'
in the file
variable above and then print(file)
to see all the details about the file you’ve just uploaded.
- If you’re trying to upload a file to a folder that is not in your Drive, make sure you share that folder with the email address listed in your
client-secret.json
first.
- You’ll have to set up a project and enable the Drive API as a prerequisite. See: https://developers.google.com/drive/api/v3/quickstart/python#prerequisites and maybe this post about the Google Sheets API I wrote.