Dreamstime

Friday 14 June 2019

Python Script To Upload Pictures To Google Photos

I was working on this Python script to upload pictures to Google Photos. Then I found out later that I couldn't get a permanent URL for my uploaded pictures - the Google Photo API doesn't provide one. And I subsequently I stopped working on it.

This little script is of no use to me. Hopefully, somebody will find some use for it. It's a waste to just throw it away since I spent quite some time working on it. "One man's junk is another man's treasure" they say.


==== BEGIN ====



#!/usr/bin/python2.4

import sys

from oauth2client import client 
from apiclient import sample_tools
from apiclient.discovery import build
from apiclient.http import HttpRequest
from httplib2 import Http


import logging


def main(argv):
  Picture_Filename = 'Test.jpg'
  
  
  logging.basicConfig(filename='debug.log',level=logging.WARNING)

  # Authenticate and construct service.
  credentials, service, flags = sample_tools.init(
      argv, 'photoslibrary', 'v1', __doc__, __file__,
      scope='https://www.googleapis.com/auth/photoslibrary')

  session = credentials.authorize(Http())

  headers = { "Content-type" :  "application/octet-stream",
              "X-Goog-Upload-Protocol" :  "raw",
#              "X-Goog-Upload-File-Name" : "Test.jpg"
              "X-Goog-Upload-File-Name" : Picture_Filename
        }
        
  photo_file = open(Picture_Filename, mode='rb')
  photo_bytes = photo_file.read()  
  
  respond, uploadToken = session.request('https://photoslibrary.googleapis.com/v1/uploads',
                                         method='POST',
                                         headers=headers,
                                         body=photo_bytes)
  

#  print "Upload Token : ", uploadToken

# --- Register photo ---
  session = credentials.authorize(Http())
  service = build('photoslibrary', 'v1', http=session)

  body = { 
#        "albumId" : u'AOp_PZqh8eHeCGgrTJS3AvQNY82q-sL8tiouksVvaX3g33MbFVelbcAnbstFFr2AMlbBej-qfj47c',
        "newMediaItems" : [
           { 
             "description": "TEST - GOOGLE PHOTOS UPLOAD",
             "simpleMediaItem" : {
               "uploadToken" : uploadToken
             }
           } 
        ]
    }

  # Call the Photo v1 API
  results = service.mediaItems().batchCreate(body=body).execute()



if __name__ == '__main__':
  main(sys.argv)

==== END ====




0 comments:

Post a Comment