やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

サンプルコードにv2のAPIを叩くコードを追記した

PythonにおけるOAuthとFusionTablesAPIのサンプルコードを改修。ParseErrorを取り除けたが、新たなエラー発生。

目標

ラズパイのCPU温度を定期的にロギングしてアップロードしたい

小目標

PythonからFusionTablesAPIを使ってinsertする。

前回

コピペミスを直すもParse Error発生

サンプルコードは古いFusion Tables APIを使っていて、その一部がエラーになっていた。

今回

古いFusion Tables APIを削除する。新しいFusion Tables APIを使うコードを追記する。

対象環境

コーディング

ソースコードのベースは前回を参照。

じつはPythonで関数を作るのははじめて。基本コピペだから問題あるまい。

Fusion Tables API v2

まずはFusion Tables API v2の仕様を確認する。

POSTするらしい。URLはhttps://www.googleapis.com/fusiontables/v2/query。あとはsqlパラメータにSQL文を付与すればいいだけ。

参考にするサンプルコード

というわけで、サンプルコードのうち、POSTしている関数を参考にする。

  def insertTemplate(self):
    print "INSERT TEMPLATE"
    data = '''{
      "tableId": %s,
      "name": "mytemplate",
      "isDefaultForTable": true,
      "body": "<p>this is a name: {name}</p>"
    }''' % (tableid)
    response = self.runRequest(
      "POST",
      "/fusiontables/v1/tables/%s/templates%s" % \
       (tableid, self.params),
      data,
      headers={'Content-Type':'application/json'})
    json_response = simplejson.loads(response)
    return json_response["templateId"]

追加するコード

上記のコードを参考にして、以下の関数を追加した。

  def testInsertV2(self):
    print "v2 Query.sql insert"
    data = '''{
      "sql": "INSERT INTO %s (Timestamp, CpuTemperature) values('%s',%s)"
    }''' % (tableid, '2011-11-11 11:11:11',11111)
    response = self.runRequest(
      "POST",
      "/fusiontables/v2/query" % \
       (tableid, self.params),
      data,
      headers={'Content-Type':'application/json'})
    json_response = simplejson.loads(response)
    print(json_response)
    return json_response

古いAPIを叩く関数を実行しないようにする

そして、メイン関数を以下のように修正する。

if __name__ == "__main__":
  api_test = RunAPITest()
  api_test.main()

  api_test.testInsertV2()

これで今回追加した関数だけ実行するようになった。ついでに、削除した関数たちの実装も削除する。別ファイルにして保存する。

実行

詳細な実行手順はローカルサーバを立ち上げてOAuth2.0認証に挑むも失敗を参照。

> python SimpleSample.py
copy and paste the url below into browser address bar and hit enter
https://accounts.google.com/o/oauth2/auth?client_id={*.apps.googleusercontent.com}&redirect_uri=http://localhost:8000&scope=https://www.googleapis.com/auth/fusiontables&response_type=code

Enter code (parameter of URL): 4/lZU_ihz138_BMCN7cgSJ88P__FxcltMxfPmtpNKQ3y8
v2 Query.sql insert
Traceback (most recent call last):
  File "SimpleSample.py", line 210, in <module>
    api_test.testInsertV2()
  File "SimpleSample.py", line 198, in testInsertV2
    (tableid, self.params),
TypeError: not all arguments converted during string formatting
exit status 1

URL文字列の修正

TypeError: not all arguments converted during string formattingエラー。URLの部分を修正し忘れていたようだ。以下のように修正した。

    response = self.runRequest(
      "POST",
      "/fusiontables/v2/query%s" % \
       (self.params),
      data,
      headers={'Content-Type':'application/json'})

Required parameter: sql

再度実行するもエラー。

> python SimpleSample.py
copy and paste the url below into browser address bar and hit enter
https://accounts.google.com/o/oauth2/auth?client_id={*.apps.googleusercontent.com}&redirect_uri=http://localhost:8000&scope=https://www.googleapis.com/auth/fusiontables&response_type=code

Enter code (parameter of URL): 4/umyYQZBxWbkazbbreQDipSGSjWAR3VtJe4cQhw6bLSo
v2 Query.sql insert
400 Bad Request
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: sql",
    "locationType": "parameter",
    "location": "sql"
   }
  ],
  "code": 400,
  "message": "Required parameter: sql"
 }
}

{u'error': {u'code': 400, u'message': u'Required parameter: sql', u'errors': [{u'locationType': u'parameter', u'domain': u'global', u'message': u'Required parameter: sql', u'reason': u'required', u'location': u'sql'}]}}

"message": "Required parameter: sql"エラー。sqlパラメータは必須。ですよね知ってます。あれ、付与したつもりなのに。

所感

基本コピペで理解していないから原因の調査が大変になりそう。