Google API Client LibraryでAPIKeyを渡して実行したがLogin Required
エラーになった。
目標
ラズパイのCPU温度を定期的にロギングしてアップロードしたい。
小目標
PythonからFusionTablesAPIを使ってinsertする。
前回
Google API Client Libraryをインストールした
対象環境
- Firefox 50.0
- Google Account
- Google Developers Console
- Google Drive
- Google Fusion Tables
- Google Apps Script
- Python 2.7
認証方法
Google API Client Libraryページのサイドメニューをみてみる。認証方法は2種類あり、アプリケーションの形態によって4パターンある、ということか?それとも、APIKeyもOAuthなのか?
API Key
とりあえず、最も簡単そうなAPI Keyから見てみる。
- [Googleの認証について調べてみた]ときのようにAPI Keyを取得する
- Fusion Tables API を有効にする
service = build('books', 'v1', developerKey="api_key")
のようにして使う
というのが概要らしい。build()
とか、唐突すぎてわけがわからない。
サンプルコード
結局、Simple API ExampleのDownloadでソースコードをみることになる。
要所を抜粋。
from apiclient.discovery import build service = build('books', 'v1', developerKey=api_key) request = service.volumes().list(source='public', q='android') response = request.execute()
from apiclient.discovery import build
がライブラリっぽい。build()
をFusion Tables版にすれば使えるのか?
どうでもいいが、名前が統一されていない。APIKeyなのかDeveloperKeyなのか。キーが多すぎてわけがわからない。
ソースコード(Fusion Tables API)
from apiclient.discovery import build api_key = '0123456789012345678901234567890123456789' service = build('fusiontables', 'v2', developerKey=api_key) tableid = '0123456789012345678901234567890123456789' rows = service.query().sql(sql="INSERT INTO %s (Timestamp, CpuTemperature) values('%s',%s)" % (tableid,'2001-02-03 04:05:06',45678)).execute()
- APIKeyはGoogleの認証キーを取得したときのAPIKeyを使う
- tableidはFusionTablesでテーブルを作成したときのファイルのURLの
docid
値を使う
このpythonコードを実行する。(コンソールでPython {ソースコードファイル名}.py
を叩く)
結果、例によってLogin Required
エラーが返ってきた。ログインしろと。
python test.py Traceback (most recent call last): File "201611290952.py", line 12, in <module> rows = service.query().sql(sql="INSERT INTO %s (Timestamp, CpuTemperature) values('%s',%s)" % (tableid,'2001-02-03 04:05:06',45678)).execute() File "C:\Python27\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper return wrapped(*args, **kwargs) File "C:\Python27\lib\site-packages\googleapiclient\http.py", line 838, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/fusiontables/v2/query?alt=json&key=AIzaSyCkQirqcbGtSN4Pfqq0xWcbERzhNhvC-mY&sql=INSERT+INTO+1b-uCPYxom04o-euZKUkptAou32PRFR8r4Az5_6zq+%28Timestamp%2C+CpuTemperature%29+values%28%272001-02-03+04%3A05%3A06%27%2C45678%29 returned "Login Required"> exit status 1
Fusion Tables APIに触ってみたときや、GASでFusionTablesAPIを叩いてみたとき、GASのdoGet関数でFusionTablesAPIを叩くときと同じエラー。
おそらく今回もそれらと同じく、Fusion Tables APIを叩くこと自体には成功している、のかもしれない。でも、それ以前にログインが必要というところでエラーになっているのだろう。
所感
で、ログインてPythonでどうやるの?そもそもPythonでログインとかできるの?ログインエラーとOAuth2.0認証は無関係なの?今私は何をやったの?