2016/10/24

Notes on the common code section for accessing Google APIs using Python

This post contains my notes after watching the 2 videos below.

Google Drive API: Uploading & Downloading Files
https://youtu.be/-7YH6rdR-tk

Accessing Google APIs: Common code walkthrough
https://youtu.be/h-gBeC9Y9cE?list=PLOU2XLYxmsILOIxBRPPhgYbuSslr50KVq

The Common Code Section

Below are the first 21 lines of code for uploading and downloading files using Google Drive API. They are the common code (with minor changes to the parameters in Line 14 - SCOPE and Line 21 - DRIVE) needed for accessing Google APIs.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from __future__ import print_function
import os

from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

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

SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store, flags) \
            if flags else tools.run(flow, store)
DRIVE = build('drive', 'v2', http=creds.authorize(Http()))

Notes and References

from __future__ import print_function

This will allow the script to run on Python 2 or Python 3. The purpose of this line is well explained at the link below.

http://stackoverflow.com/questions/7075082/what-is-future-in-python-used-for-and-how-when-to-use-it-and-how-it-works

import os

http://stackoverflow.com/questions/2724348/should-i-use-import-os-path-or-import-os

from apiclient.discovery import build

It creates a service endpoint (service object) for interacting with the API (visit below link for more detail).

https://developers.google.com/api-client-library/python/start/get_started


from httplib2 import Http

It's needed for creating the http object for sign in request.

https://developers.google.com/api-client-library/python/auth/service-accounts


from oauth2client import file, client, tools

Token storage from OAuth2client.file and utility functions to create and run the OAuth flow respectively.

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

This section of code is for backward compatibility with Python 2.3-2.6. See below excerpt from http://wescpy.blogspot.tw/2015/04/google-apis-migrating-from-toolsrun-to.html.


SCOPES = 'https://www.googleapis.com/auth/drive.file'

Oauth scopes express the permissions the user is requested to authorize for the app. More strings can be added if more scopes are needed (SCOPES = # one or more scopes (strings)).

The sample below is from http://wescpy.blogspot.tw/2014/11/authorized-google-api-access-from-python.html.


For a list of available Google Drive API v2 Scopes, visit https://developers.google.com/drive/v2/web/scopes.


For a list of available Google Drive API v3 Scopes (and other OAuth 2.0 Scopes for Google APIs), visit https://developers.google.com/identity/protocols/googlescopes#drivev3.


store = file.Storage('storage.json')

When the app. is granted access, the server sends back an access token which is stored in 'storage.jason'. 

creds = store.get()

Get a valid access token with which to make authorized API calls. 

if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store, flags) \
            if flags else tools.run(flow, store)

If the credentials are missing or invalid, an OAuth flow will be created and executed to get a valid access token and store it in 'storage.jason'.

Note:

1. The file 'client_secret.json' is stored in the same folder where this Python script is stored and executed.

2. The creds part is made so to allow backward compatibility with tools.run(). See "Google APIs: migrating from tools.run() to tools.run_flow()" at
http://wescpy.blogspot.tw/2015/04/google-apis-migrating-from-toolsrun-to.html

DRIVE = build('drive', 'v2', http=creds.authorize(Http()))

Once a valid access token is obtained, create a service endpoint to that API. The API string and its version need to be specified. The last parameter signs the http call with the credentials.

A window similar to the one below is created when "DRIVE = build('drive', 'v2', http=creds.authorize(Http()))" is executed.


No comments:

Post a Comment