Upload images to Google Drive with Python

I made a program to upload images to Google Drive with Python.

environment

Windows 7 Professional SP1 64bit Python 3.6.1 (64bit) pip 9.0.1 google-api-python-client 1.6.2 PyDrive 1.3.1

Package installation

Install "google-api-python-client" and "PyDrive".

command prompt


>pip install google-api-python-client
>pip install PyDrive

An error occurred during the installation of PyDrive, so I solved it by the following method. http://qiita.com/akabei/items/da70ebf61cc413d5ff0d

Get OAuth client ID

You will need your "Client ID" and "Client Secret" to access Google Drive, so get them.

Go to the Google Developers Console and create a project. https://console.developers.google.com/

aaa.png

Enter the project name appropriately.

aaa.png

Create an "OAuth Client ID" from your credentials.

aaa.png

When the message "To create an OAuth client ID, you must first set the service name on the consent screen." Is displayed, set the consent screen.

aaa.png

From the OAuth consent screen, enter the "service name to be displayed to the user" appropriately.

aaa.png

When the creation of client ID is displayed, select "Other", enter an appropriate name, and press Create.

aaa.png

Now you can get the "Client ID" and "Client Secret". Make a note of it so that you will use it later.

aaa.png

Or download the JSON file from your credentials. The JSON file contains the "Client ID" and "Client Secret".

aaa.png

Enable Google Drive API

Continue to select the Google Apps API Drive API from the Google Developers Console library.

aaa.png

The following screen will be displayed. Click "Enable" to enable the Google Drive API.

aaa.png

When "Enable" changes to "Disable", the Google Drive API is enabled. (No Google Drive API settings required)

aaa.png

Now you're ready to access Google Drive.

Program creation

Create a program (imageupload.py) to upload images to Google Drive. This time I'm using CommandLineAuth () because it's called from the command line.

imageupload.py


from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.CommandLineAuth()
drive = GoogleDrive(gauth)

f = drive.CreateFile({'title': 'test.jpg', 'mimeType': 'image/jpeg'})
f.SetContentFile('test.jpg')
f.Upload()

Create a settings file (settings.yaml) in the same folder as the program. Enter the "Client ID" and "Client Secret" obtained above.

settings.yaml


client_config_backend: settings
client_config:
  client_id: <Client ID>
  client_secret: <Client secret>

save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json

get_refresh_token: True

oauth_scope:
  - https://www.googleapis.com/auth/drive.file
  - https://www.googleapis.com/auth/drive.install

Prepare the image (test.jpg) used in this test in the same folder as the program.

test.jpg

Program execution

Run the program from the command prompt. At the first execution, you will be prompted to enter the verification code, so display the displayed URL in your browser.

command prompt


>python imageupload.py
C:\Python36\lib\site-packages\oauth2client\_helpers.py:255: UserWarning: Cannot access credentials.json: No such file o
r directory
  warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
Go to the following link in your browser:

    https://accounts.google.com/o/oauth2/auth?client_id=915107419881-unme2nu12t3d5sf10cmpudgo20jq3mtg.apps.googleuserco
ntent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file+h
ttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.install&access_type=offline&response_type=code&approval_prompt=force

Enter verification code: 

The browser will display a screen to approve access to Google Drive, so "Allow" it.

aaa.png

The identification code will be displayed in the browser, so copy it and paste it into the command prompt.

aaa.png

After pasting the identification code, enter the enter key.

command prompt


Enter verification code: 4/aiZHOmoP3Ufz5Y-d8BvTFq8-IL7Do2GK7FOAAurccN4
Authentication successful.

If it finishes normally, the image will be uploaded to Google Drive. (You do not need to enter the identification code from the second time onward.)

Google drive https://drive.google.com/drive/

aaa.png

Upload to folder

"Folder ID" is required when uploading to a folder in Google Drive. Open the folder you want to upload in your browser and the last part of the displayed URL is the folder ID.

aaa.png

You can upload to that folder by specifying the folder ID in the parameter of CreateFile ().

imageupload.py


from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.CommandLineAuth()
drive = GoogleDrive(gauth)

folder_id = '0B5fATn-vXv5wZ0RlM1JpQzdFTk0'
f = drive.CreateFile({'title': 'test.jpg',
                      'mimeType': 'image/jpeg',
                      'parents': [{'kind': 'drive#fileLink', 'id':folder_id}]})
f.SetContentFile('test.jpg')
f.Upload()

reference

I referred to the following site.

Using Google Drive with PyDrive http://python.keicode.com/advanced/pydrive.php

Recommended Posts

Upload images to Google Drive with Python
Upload files to Google Drive with Lambda (Python)
Access Google Drive with Python
Upload to a shared drive with Google Drive API V3
How to search Google Drive with Google Colaboratory
Regularly upload files to Google Drive using the Google Drive API in Python
How to upload with Heroku, Flask, Python, Git (4)
Convert PDFs to images in bulk with Python
Upload images to S3 with GUI using tkinter
Connect to BigQuery with Python
Upload JPG file using Google Drive API in Python
Connect to Wikipedia with Python
Study Python with Google Colaboratory
How to upload with Heroku, Flask, Python, Git (Part 3)
How to load files in Google Drive with Google Colaboratory
Easy way to scrape with python using Google Colab
How to upload with Heroku, Flask, Python, Git (Part 2)
Switch python to 2.7 with alternatives
Write to csv with Python
Mount google drive with google-drive-ocamlfuse
Google Drive Api Tips (Python)
How to extract any appointment in Google Calendar with Python
Send experiment results (text and images) to slack with Python
Convert images to sepia toning with PIL (Python Imaging Library)
How to upload files to Cloud Storage with Firebase's python SDK
Post a message to Google Hangouts Chat with a thread (Python)
Upload and delete files to Google Cloud Storages with django-storage
Python: Extract file information from shared drive with Google Drive API
Number recognition in images with Python
Python: How to use async with
Link to get started with python
[Python] Write to csv file with Python
How to collect images in Python
Create folders from '01' to '12' with python
Nice to meet you with python
Try to operate Facebook with Python
Output to csv file with Python
Download Google Drive files in Python
MP3 to WAV conversion with Python
To do tail recursion with Python2
How to get started with Python
What to do with PYTHON release?
Post images from Python to Tumblr
Animate multiple still images with Python
Unable to install Python with pyenv
How to use FTP with Python
Load gif images with Python + OpenCV
How to calculate date with python
[Python] Collect images easily with icrawler!
Selenium and python to open google
Easily post to twitter with Python 3
I want to debug with Python
Working with DICOM images in Python
Upload and download images with falcon
File upload to Azure Storage (Python)
How to connect to Cloud Firestore from Google Cloud Functions with python code
Try to display google map and geospatial information authority map with python
Image upload & download to Azure Storage. With Python + requests + REST API
I tried to automatically collect images of Kanna Hashimoto with Python! !!
Upload file to GCP's Cloud Storage (GCS) ~ Load with local Python
The fastest way to get camera images regularly with python opencv