LoginSignup
2
1

More than 5 years have passed since last update.

Google BigQuery (オライリー本)で出てくるauth.py

Posted at

はじめに

オライリー本に出てくるauth.pyが古くて実行できなかったので、最新版に書き直してみた。

2017年4月8日(土)動作確認済み

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'
# 以下の値は自分のサービスアカウント用の秘密鍵のファイルへフルパスにすること
KEY_FILE = '<自分のサービスアカウント用の秘密鍵名>.json'

def get_oauth_creds():

    # ユーザークレデンシャルの生成。
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        KEY_FILE, 
        BIGQUERY_SCOPE
    )
    # 最新のクレデンシャルに更新。
    credentials.refresh(httplib2.Http())
    return credentials


def print_creds(credentials):
    '''HTTPリクエスト中で使用する許可ヘッダを出力する。'''
    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()

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1