Tableau 10.1新機能:『Tableau Document API』について

2016.11.06

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Tableau 10.1新機能シリーズ、当エントリでは『Tableau Document API』についてご紹介したいと思います。

tableau101-image

Tableau Document APIとは

Tableau Document APIとは、v10から利用出来るようになったAPIの事です。GitHub及びドキュメントのページは以下となります。

tableau-document-api_01

Tableau Document APIはTableauワークブックやデータソースファイルをプログラムで更新するサポート方法を提供します。これらのファイルの変更を直接XMLをハッキングして行っていた場合、このSDKが役に立つことでしょう。機能としては以下のものを含みます。

  • Tableau 9.x系及び10.x系のワークブック及びデータソースファイルにアクセス可能。(tdsx及びtwbxファイルを含む)
  • ワークブック及びデータソースから接続情報を取得
    • サーバー名
    • ユーザー名
    • データベース名
    • 認証タイプ
    • 接続タイプ
  • ワークブック及びデータソースの接続情報を更新
    • サーバー名
    • ユーザー名
    • データベース名
  • ワークブック及びデータソースからフィールド情報を取得
    • データソースの全てのフィールド
    • ワークブック内の特定のシートで使用している全てのフィールドを取得
  • 以下の部分については現状未サポート。
    • ファイルをスクラッチから作成
    • ワークブックやデータソースに抽出ファイルを追加
    • フィールド情報の更新

実行環境のインストール

公式ドキュメントを参考に書いてみたPythonプログラムが以下の内容となります。データソースの情報とワークブックのシートに関する情報を一覧表示してみました。

環境導入は至って簡単。pipが利用できる環境でtableaudocumentapiをインストールするだけ。Python2.7及び3.x系双方に対応しているようです。

$ pip --version
pip 7.0.1 from /Library/Python/2.7/site-packages/pip-7.0.1-py2.7.egg (python 2.7)
$
$ sudo pip install tableaudocumentapi
:
Collecting tableaudocumentapi
  Downloading tableaudocumentapi-0.5-py2.py3-none-any.whl
Installing collected packages: tableaudocumentapi
Successfully installed tableaudocumentapi-0.5

サンプルコードの紹介

tableau-document-api-sample.py

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

from tableaudocumentapi import Workbook

sourceWB = Workbook('/Users/xxxx/Desktop/tableau-viz/VIZ:Developers.IO.twb');

print("## データソース一覧の表示")
for ds in sourceWB.datasources:
  for cn in ds.connections:
    print("----");
    print(cn.server);
    print(cn.dbname);
    print(cn.username);

sourceWB = Workbook('/Users/xxxx/Desktop/tableau-viz/日本分析.twbx')
print("")
print("## ワークシート一覧の表示")
for ws in sourceWB.worksheets:
  print(ws)

実行結果が以下となります。

$ python tableau-document-api-sample.py 
## データソース一覧の表示
----
cm-redshift-hostname.com
cmredshiftdb
cmdbuser
:

## ワークシート一覧の表示
ゴジラの上陸経路
ヒートマップ
マグニチュード
各市町村就業人口
各産業就業人口
各選手の成績
地価総額 累計
地震の時系列表示
地震マップ
年棒/年齢/体重/身長での比較
教育
散布図
株価
産業地図

また、サイトで公開されているサンプルコードでも分かり易く記載されている物がありますので展開してみます。

データソース内のフィールド一覧を表示

show_fields.py

############################################################
# Step 1)  Use Datasource object from the Document API
############################################################
from tableaudocumentapi import Datasource

############################################################
# Step 2)  Open the .tds we want to inspect
############################################################
sourceTDS = Datasource.from_file('world.tds')

############################################################
# Step 3)  Print out all of the fields and what type they are
############################################################
print('----------------------------------------------------------')
print('--- {} total fields in this datasource'.format(len(sourceTDS.fields)))
print('----------------------------------------------------------')
for count, field in enumerate(sourceTDS.fields.values()):
    print('{:>4}: {} is a {}'.format(count+1, field.name, field.datatype))
    blank_line = False
    if field.calculation:
        print('      the formula is {}'.format(field.calculation))
        blank_line = True
    if field.default_aggregation:
        print('      the default aggregation is {}'.format(field.default_aggregation))
        blank_line = True
    if field.description:
        print('      the description is {}'.format(field.description))

    if blank_line:
        print('')
print('----------------------------------------------------------')

データソースの情報を表示

list_tds_info.py

############################################################
# Step 1)  Use Datasource object from the Document API
############################################################
from tableaudocumentapi import Datasource

############################################################
# Step 2)  Open the .tds we want to replicate
############################################################
sourceTDS = Datasource.from_file('world.tds')

############################################################
# Step 3)  List out info from the TDS
############################################################
print('----------------------------------------------------------')
print('-- Info for our .tds:')
print('--   name:\t{0}'.format(sourceTDS.name))
print('--   version:\t{0}'.format(sourceTDS.version))
print('----------------------------------------------------------')

ワークブックの複製

replicate_workbook.py

import csv              # so we can work with our database list (in a CSV file)

############################################################
# Step 1)  Use Workbook object from the Document API
############################################################
from tableaudocumentapi import Workbook

############################################################
# Step 2)  Open the .twb we want to replicate
############################################################
sourceWB = Workbook('sample-superstore.twb')

############################################################
# Step 3)  Use a database list (in CSV), loop thru and
#          create new .twb's with their settings
############################################################
with open('databases.csv') as csvfile:
    databases = csv.DictReader(csvfile, delimiter=',', quotechar='"')
    for row in databases:
        # Set our unique values for this database
        sourceWB.datasources[0].connections[0].server = row['Server']
        sourceWB.datasources[0].connections[0].dbname = row['Database']
        sourceWB.datasources[0].connections[0].username = row['User']
        # Save our newly created .twb with the new file name
        sourceWB.save_as(row['DBFriendlyName'] + ' - Superstore' + '.twb')

まとめ

以上、Tableau Document APIに関する内容のご紹介でした。まだまだ出来る事は限られていますが、今後の機能追加・改善等で対象要素の修正等が自由に出来るようになってくると夢も広がりそうですね。こちらからは以上です。