Automating Analytics in Tableau — Python & Tabcmd | by Eshwaran Venkat | Towards Data Science

Tableau has been recognized as a leading tool in Analytics and Business Intelligence Platforms for seven consecutive years by Gartner. BI/Data teams in companies of all shapes and sizes in nearly every industrial sector develop dashboards to effectively communicate key business metrics across the organization.
One major advantage of using Tableau (which is often overlooked) is that it exposes a public API to programmatically handle nearly all tasks that can be carried out over the application GUI — Including administration.
This is the part where Python comes in. The scripting capability and support from a vast number of libraries makes it a popular choice to handle end-to-end process automation in BI workflows.
Before You Proceed...
To effectively use the integrations, the Tableau workbook(s) should be available on one of the following:
1. Tableau Server Lets you host workbooks and data sources in-house on your organisational servers or using cloud service providers.
2. Tableau OnlineTableau manages the server infrastructure and you can host your workbooks through them at some additional cost.
It’s often good practice to have workbooks hosted on a Tableau server through one of the above mentioned methods — especially if your dashboards are viewed frequently by multiple parties and involve periodic data refreshes (Daily/Hourly).
Tableau Online has a 14 day free-trial with some sample workbooks loaded in by default. You can create a free trial account to try out some of the test integrations and code snippets listed below.
Upon creation of a Tableau Online account, save the credentials for username, password, tableau server address and site name. A single tableau server can have multiple sites and each of these sites hosts a collection of workbooks and datasources.
There are a number of ways to integrate Python with Tableau Server, each based off a different use-case.
Tableau Server Client (TSC) library (Python 3.5 or later)
Tableau Server Client (TSC) library (Python 3.5 or later)
Probably the best option out there for performing server related tasks from a Python script. It’s an open source project managed by Tableau that wraps around the Tableau Server REST API.
pip install tableauserverclient
2. TabPy libraryAllows you to embed and execute Python scripts within Tableau’s table calculations. It essentially allows Tableau to remotely execute Python code.
pip install tabpy
3. Using Requests library to directly consume the Tableau Server REST API .A more bare-bones approach but you can make Tableau work in any way you deem fit as allowed by the API.
Others integration routes and variants include:
1. JupyTab
Brings Jupyter Notebook data into Tableau visualizations.
pip install jupytab
2. Tabcmd Issue commands to Tableau Server from the Windows Shell — Unsupported for Mac/Linux natively, but there is a hack.
Download Tabcmd for Tableau Server
Tabcmd executions can be primarily automated by setting them up inside a batch file under a scheduled task. Add Tabcmd to your windows PATH variable or switch over to the directory where it's installed to run its commands.
You can execute tabcmd commands from within Python source code by using the os or subprocess modules. Construct tabcmd statements as strings and pass them into the shell using os.system()orsubprocess.call()functions
You can find more projects with support for other languages (such as JavaScript) in Tableau’s GitHub Page
We’ll focus on the usage of TSC and Tabcmd here.
The dummy variables listed below will be assumed to be accessible for each TSC snippet. Substitute these with your own credentials.
tableau_user = 'cricks@gmail.com'tableau_passwd = '123'tableau_server = 'http://172.16.22.2/'tableau_server_site = 'my_site'server_version = '3.7'
For Tableau Online, the tableau_server field would look something like this: prod-apnortheast-a.online.tableau.com based on your server location.
Each of the following sections details how to perform a particular task on the Tableau Server using both TSC and Tabcmd.
TSC
Tabcmd
> tabcmd login -s http://172.16.22.2/ -t my_site -u cricks@gmail.com -p 123
Each parameter of the credential is passed as a flag in the shell.
The output should look like this:
===== redirecting to http://172.16.22.2/auth===== Signed out===== Creating new session=====     Server:   http://172.16.22.2/=====     Username: cricks@gmail.com=====     Site:     my_site===== Connecting to the server...===== Signing in...===== Succeeded
In the event of a failed authentication in either routes, check your user privileges/user authorization with a Tableau Server admin.
The ‘Superstore’ workbook is available as a sample in all Tableau distributions. It will be the default workbook in the demonstrations for our code snippets.
Finding the Workbook & Downloading it as a .twbx file
TSCA workbook can be found by using — TSC.Pager() — TSC.RequestOptions() with a TSC.Filter() on workbooks.get().
TSC returns a workbook object with attributes such as workbook ID, workbook name, etc. Each of these options is detailed as a function in the following gist.
A workbook can be downloaded as twbx (Tableau packaged workbook) with- TSC.Server().workbooks.download(workbook_id)
You can retrieve the workbook’s ID on the server by referencing the id attribute on the workbook object.
Tabcmd
Tabcmd keeping it short and simple:
tabcmd get “/workbooks/Superstore.twbx”
There could be a couple of caveats especially with permissions for the get command in Tabcmd. Make sure to go through the full checklist here. You can use get to download the workbook as a PDF or PNG as well.
We can query a particular view within the workbook and apply a filter to it.
How it works:We issue a request for a view with filters as parameters. The API applies the request to the view and fetches a snapshot back to the requesting client.
Before Filter:
After Filter for Region = West:
TSC
Assuming workbook id can be fetched, we’ll use it as a dummy variable.
view_items contains a list of view objects. A view object has attributes such as id, workbook_id, name, csv. A personal favorite is the total_views attribute which returns the total number of times that the currently referenced view has been seen by users on the Server.
We are required to “populate” views as PDFs because it allows TSC to fetch only necessary attributes from over the web. The workbook or view object contains a reference to all other attributes of that object on the server. When one of these objects needs to be populated, TSC makes the request fetch the required attributes to satisfy the populate params.
Images can be saved as PNG with ImageRequestOptions() and CSVs can be saved with CSVRequestOptions().
See the docs for their usage here.
Tabcmd
The export command takes in the URL of the specified view and optional parameters for download options.
tabcmd export -t my_site "Superstore/Overview?refresh=yes&Region=West" --pdf --pagesize a4 --pagelayout landscape -f "Overview.pdf"
The view can be exported as a PNG or CSV too.
The URI specified within quotes is exactly the same as the sub-string of the URL used to access the view on Tableau Server over a browser.
Here’s what the URL on the browser would be for the same command:
http://172.16.22.2/#/site/my_site/views/Superstore/Overview?Region=West
This helps experiment with what a view would look like on the browser before using Tabcmd to export it locally.
'refresh=yes' forces a server side refresh on the view and fetches the most up-to-date results.
Apply multiple filters by separating them out in the params with an '&'
Dates can be filtered as: ‘..?report_date=2020–01–01'
One of Tableau’s core features as a software has been its ability to allow users to handle the data sources, extracts and connections of data that feeds into the visualizations.
TSC
the datasource object can be filtered or paged through as well, similar to workbook or view objects.
Tabcmd
tabcmd refreshextracts --datasource sales_ds
Both TSC and Tabcmd allow you to perform crucial CRUD operations on Data Sources, Connections, Workbooks, Views, Users, etc.
While TSC is natively OS agnostic, Tabcmd is still sufficient to carry out most day-to-day tasks on the server, provided you have a windows system or are able to configure it to run manually on Mac/Linux.
One particular use-case where TSC outbids Tabcmd is its ability to handle a large number of requests to the server in parallel. With Tabcmd, requests are always serialized per shell session. TSC can be multithreaded to tens or hundreds of workers providing a massive boost in the performance for its server requests. On Python, you can implement the ThreadPoolExecutor() with a map() on a list to a function that uses TSC and have it work to your advantage.
This could potentially be useful in kick-starting fast and efficient BI reporting. Bringing this together with Python for Google Sheets/Excel or Python for SQL can supercharge your workflow.
Tableau has rich documentation on using both TSC and Tabcmd. The snippets in this article scratch the surface of the multitude of actions that can be performed with them on a Tableau Server. Check them out in detail below.
TableauServerClient Docs
Tabcmd Docs
VisualBI blog on basic TabcmdTake command with TabcmdTableau Server Client and REST API demo
VisualBI blog on basic Tabcmd
Take command with Tabcmd
Tableau Server Client and REST API demo
Hopefully, this was a gentle enough introduction to get you on your feet and to get started with these integrations.