With the release of the tableau_tools package, the TableauDatasourceGenerator class is now available for creating a data source from scratch programmatically. But what if you just want to modify an existing data source? There are several good use cases for it:
- Adding in data source filters across the board
- Transforming a TDS into an extract with a given set of filters
- Renaming columns for different template variations (this can facilitate translations) but more broadly could also use the correct terminology for a given Site
With the newest update to tableau_tools (3.0.1), available via PyPi or GitHub, you can now do some of these things to an existing data source programmatically using the existing TableauDatasource class.
When you create a new TableauDatasource object, there is now a TableauDatasourceGenerator object created internally, which allows for the addition of new elements that were not originally in the base data source file.
Because it is such a common use case, to add an extract to a TDS, there is now a direct add_extract method of the TableauDatasource class. For other transformations, you can access the TableauDatasource.ds_generator property, which is a reference to the embedded TableauDatasourceGenerator object. Any thing that you add (calculations, columns, data source filters, extract filters) will be added to the existing TDS file whenever you call the TableauDatasource.get_datasource_xml() method. This method is also called when calling the save_file(filename_no_extension, save_to_directory) method.
Here’s an example, where I have an existing TDS file that I built in Desktop, and I want to add a calculation to it and make it an extract.
<pre>file_name = u'desktop sqlserver.tds' ds_str = open(file_dir + file_name, 'r') ds = TableauDatasource(ds_str.read(), logger) ds.ds_generator.add_calculation('YEAR([OrderDate])', 'Year Order Date', 'dimension', 'continuous', 'integer') ds.add_extract('Awesomeextract.tde') ds.save_file('tds transformed into tdsx', file_dir) ds_str.close()</pre>
This is just a 3.0.1 release to show that it is possible. More testing and features to come.