Auth.py from Google BigQuery (O'Reilly book)

Introduction

The ʻauth.py` that appears in the O'Reilly book was too old to run, so I rewrote it to the latest version.

Operation confirmed on Saturday, April 8, 2017

auth.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import httplib2
import json
from apiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials

BIGQUERY_SCOPE = 'https://www.googleapis.com/auth/bigquery'
#The following values should be the full path to the private key file for your service account
KEY_FILE = '<Private key name for your service account>.json'

def get_oauth_creds():

    #User credential generation.
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
    	KEY_FILE, 
    	BIGQUERY_SCOPE
    )
    #Updated to the latest credentials.
    credentials.refresh(httplib2.Http())
    return credentials


def print_creds(credentials):
    '''Output the permission header used in the HTTP request.'''
    cred_dict = json.loads(credentials.to_json())
    if 'access_token' in cred_dict:
        print 'Authorization: Bearer %s' % (cred_dict['access_token'],)
    else:
        print 'creds: %s' % (cred_dict,)


def main():
    print_creds(get_oauth_creds())

if __name__ == "__main__":
    main()

reference

-[Python] API authentication method for various Google services (v.2) -First Analytics API: Python Quick Start for Service Accounts

Recommended Posts

Auth.py from Google BigQuery (O'Reilly book)
Use BigQuery from python.
Run BigQuery from Lambda
Scraping immediately from google images!