Ichta
Ichta

Reputation: 308

Return all possible filter values with tableau server client for python

I am using the Tableau Server REST API via the python server client library (https://github.com/tableau/server-client-python) to automatically download pdf versions of several tableau workbook views.

For each pdf export I am filtering the Tableau view according to set parameter values. Currently, all possible parameter values are specified manually but I would like to instead find all possible options and loop over those (generating one pdf per filter option). Is that possible?

A small example code where a tableau view is filtered on the parameter country and possible values "Sweden" and "Norway":

import tableauserverclient as TSC 

Parameters = [{"Parameter Name" : "Country", "ParameterValue" : "Sweden"}, 
              {"Parameter Name" : "Country", "ParameterValue" : "Norway"}]

for params in Parameters:
      image_req_options = TSC.PDFRequestOptions()
      image_req_options.vf(params["ParameterName"], params["ParameterValue"]

      server.views.populate_pdf(view, image_req_options)
      with open('output_pdf_{}.pdf'.format(params["ParameterValue"]), 'wb') as f:
           f.write(view.pdf)

Instead of defining the Parameters list of dictionaries I would like to find all possible ParameterValues for the Parameter Country.

Upvotes: 2

Views: 2671

Answers (1)

saliustripe
saliustripe

Reputation: 96

You can achieve this with by creating a separate private workbook using the same published datasource and underlying filters, then using the ViewItem class method populate_csv to return the values required. You will not be able to return hardcoded parameters, but you could use dynamic parameters loaded from a dimension field. Learn more about dynamic parameters here.

The populate_csv function returns the same data as the "Download Crosstab" option from Tableau Cloud, selecting the first option that appears on a view based on alphabetical order.

  1. Make sure your workbook's parameters are generated from a dimension field
  2. Create and publish a new view: drop your dimension you want to filter on on 'rows', and nothing else. It will look like an empty crosstab.
  3. Extract row values into pandas DataFrame object.
import tempfile
import pandas as pd

new_view_id = "view_id_string_here"

tableau_auth = TSC.PersonalAccessTokenAuth(your_auth)
server = TSC.Server(your_server)

with server.auth.sign_in(tableau_auth):
    view = server.views.get_by_id(new_view_id)
    server.views.populate_csv(view)
    with tempfile.TemporaryFile() as file:
        for chunk in view.csv:
            file.write(chunk)
        file.seek(0)
        df = pd.read_csv(file)

This dataframe should contain all dimension values in the default view of the view you created and published. You can use this as you require.

Upvotes: 0

Related Questions