Upload JPG file using Google Drive API in Python

Overview

Upload the image file to Google Drive with python. Implement it quietly according to Quickstart.

Preparation

$ pip install --upgrade google-api-python-client 

Implementation

Add the part to upload the jpg by referring to Quickstart sample code.

Source code

The code below uploads a file called "sample.jpg " in the same directory after getting the credentials.

google_drive_uploadjpg.py


# -*- coding: utf-8 -*-
from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

import requests

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

#https in quickstart://www.googleapis.com/auth/drive.metadata.readonly but not upload permission
#Use the following of FullScope that can also be uploaded(I searched for SCOPE that can only upload, but I couldn't find it...)
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
#Application name entered when creating the project
APPLICATION_NAME = 'Drive API Quickstart'

def get_credentials():
    """
    (quickstart.Japanese translation of py)
Store valid user authentication(Locally stored credentials)Get from
If nothing is stored locally or if the stored credentials are invalid
Get new credentials with OAuth2 flow
    (Japanese translation up to here)

・ If you execute it as it is, the browser will open automatically and you will be taken to the authentication screen.
・ When executing python--noauth_local_The URL is displayed on the console with the webserver option
When you enter the displayed URL in the browser, the authentication screen is displayed, and enter the code that appears after authentication on the console.
    :return:Obtained credentials
    """

    # ~/.credentials/drive-python-quickstart.Save credentials in json
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        print('Storing credentials to ' + credential_path)
    return credentials

def upload_jpg(credentials, jpgfile):
    url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
    size = os.path.getsize(jpgfile)
    headers = {
        'Host':'www.googleapis.com',
        'Content-Type':'image/jpeg',
        'Content-Length': str(size),
        'Authorization': 'Bearer ' + credentials.access_token,
    }
    f = open(jpgfile, "rb")
    requests.post(url, headers=headers,data=f)

    return

def main():
    #Get credentials
    credentials = get_credentials()

    #jpgfile Upload(REST)
    upload_jpg(credentials, "sample.jpg ")

if __name__ == '__main__':
    main()

Operation check

python google_drive_uploadjpg.py

If the image has been uploaded to Google Drive by executing, it is okay.

Bonus: Upload with curl

Upload is a REST API, so you can also upload with curl.

uploadjpg_curl.sh


curl -X POST \
-H 'Host: www.googleapis.com' \
-H 'Content-Type: image/jpeg' \
-H 'Content-Length: number_of_bytes_in_file' \
-H 'Authorization: Bearer your_auth_token' \
-T sample.jpg \
https://www.googleapis.com/upload/drive/v3/files?uploadType=media

For number_of_bytes_in_file, enter the size of sample.jpg For your_auth_token, enter the access_token described in ~ / .credentials / drive-python-quickstart.json.

Complete source code

I put it below. Putting your client_secret.json in the same directory should work. https://github.com/yakan10/google_drive_uploadjpg

Supplement: Flow of creating a new project on the Google API console

It is almost a Japanese translation of Quickstart Step1.

  1. Go to Google APIs
  2. Select "Create Project" to continue
  3. Go to "API Enabled"-> Credentials
  4. Cancel with "Add Credentials to Project"
  5. "OAuth consent screen" tab-> Enter your email address and service name to be displayed to the user and save
  6. "Credentials" tab-> "Create Credentials"-> OAuth Client ID
  7. Select "Other" and enter "Drive API Quickstart" as the name-> Create
  8. The OAuth client dialog is displayed, but for the time being, "OK"
  9. DL the file with the download icon next to the ID you created earlier in "OAuth 2.0 Client ID"
  10. Name the DL file "client_secret.json"

Recommended Posts

Upload JPG file using Google Drive API in Python
Regularly upload files to Google Drive using the Google Drive API in Python
Google Drive Api Tips (Python)
Speech file recognition by Google Speech API v2 using Python
[Python3] Google translate google translate without using api
Download Google Drive files in Python
Python: Extract file information from shared drive with Google Drive API
Mouse operation using Windows API in Python
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Tweet using the Twitter API in Python
Get Google Fit API data in Python
Get Youtube data in Python using Youtube Data API
Creating Google Spreadsheet using Python / Google Data API
[SEO] Flow / sample code when using Google Analytics API in Python
Upload images to Google Drive with Python
Create a GIF file using Pillow in Python
Run Google Analytics API (core v3) in python
Try using the BitFlyer Ligntning API in Python
Get image URL using Flickr API in Python
Let's judge emotions using Emotion API in Python
Upload files to Google Drive with Lambda (Python)
Anonymous upload of images using Imgur API (using Python)
[WP REST API v2] Upload images in Python
Create a MIDI file in Python using pretty_midi
Try using ChatWork API and Qiita API in Python
Try using the DropBox Core API in Python
File operations in Python
File processing in Python
Google Drive file move
Evernote API in Python
File operations in Python
C API in Python 3
Google Drive API Set File Permission (Set permissions on Google Drive files)
Make a copy of a Google Drive file from Python
Collectively register data in Firestore using csv file in Python
Initial settings when using the foursquare API in python
Get LEAD data using Marketo's REST API in Python
[Python] Get insight data using Google My Business API
OpenVINO using Inference Engine Python API in PC environment
Create your first GDSII file in Python using gdspy
Speech transcription procedure using Python and Google Cloud Speech API
Using the National Diet Library Search API in Python
Upload to a shared drive with Google Drive API V3
Upload as open data using CKAN API in Python & automatically link with Github Actions
Hit Mastodon's API in Python
Download the file in Python
Upload videos using YouTube API
Blender Python API in Houdini (Python 3)
Access Google Drive with Python
Translate using googletrans in Python
Using Python mode in Processing
Inflating text data by retranslation using google translate in Python
Predict gender from name using Gender API and Pykakasi in Python
Google search for the last line of the file in Python
Issue reverse geocoding in Japanese with Python Google Maps API
Play with YouTube Data API v3 using Google API Python Client
GUI programming in Python using Appjar
Getting the arXiv API in Python
Precautions when using pit in Python
Data acquisition using python googlemap api