tableau_tools Python Library

repository·6.0.0·Indexed 42 days ago

https://github.com/bryanthowell-tableau/tableau_tools

A Python library for Tableau Server administration and programmatic manipulation of Tableau files. It provides a high-level interface for the Tableau REST API via the `tableau_rest_api` sub-package, tools for modifying Tableau document XML structures (`.twb`, `.tds`, `.tde`) through `tableau_documents`, a `tabcmd` class for triggering actions like extract refreshes, and access to the Tableau Repository.

Tokens
19K
Snippets
45
Records
77
Agent score
3%

What's inside tableau_tools

  1. Overview of tableau_tools sub-packages

    6.0.0

    The tableau_tools library is designed to simplify Tableau Server administration and file manipulation. It is organized into several key functional areas:

    • tableau_rest_api: A complete implementation of the Tableau Server REST API. Use this for interacting with Tableau Server (e.g., managing users, sites, content, and permissions).
    • tableau_documents: A sub-package for working directly with Tableau files (.twb, .tds, .tde, etc.). It allows for programmatic manipulations like changing data sources, modifying parameters, or defining calculated fields.
    • tabcmd: A class for triggering actions similar to the Tableau Command Line utility, such as extract refreshes.
    • tableau_repository: Provides access to the Tableau Repository for querying and managing sessions.
  2. Understand the tableau_tools library structure

    6.0.0

    The library is organized into several functional sub-packages:

    • tableau_rest_api: Contains methods for interacting with various REST API endpoints (e.g., alert, datasource, extract, user, workbook, etc.).
    • tableau_documents: Handles document-related logic (e.g., tableau_workbook, tableau_datasource, tableau_connection).
    • tableau_repository: Interface for the Tableau PostgreSQL repository.
    • tableau_server_rest: Core REST server interactions.
    • logger & logging_methods: Logging utilities.
    • tableau_exceptions: Custom exception classes.
    • Legacy/Unsupported modules: tabcmd, tableau_http, and tableau_emailer (unsupported).
  3. Lookup LUIDs by name

    6.0.0

    If you need to find the Locally Unique Identifier (LUID) for a piece of content using its name, use the lookup methods available in the main TableauServerRest class. While most methods in the library can automatically perform a lookup if you pass a name instead of an LUID, using explicit lookup methods is useful when you need the LUID specifically to generate subsequent actions.

    Example method: TableauServerRest.query_group_luid(name)

    Note: Passing LUIDs directly is faster than passing names, especially when processing large lists.

  4. Iterate through datasources using DatasourceFileInterface

    6.0.0

    To perform bulk operations on datasources across different file types (e.g., changing a connection string in both .twb and .tds files), use the DatasourceFileInterface.datasources property. This provides a consistent way to access all TableauDatasource objects regardless of whether the parent is a workbook or a standalone datasource file.

    from tableau_tools.tableau_documents import *
    
    list_of_files = ['A.twb', 'B.tdsx', 'C.twbx', 'D.tds']
    for file in list_of_files:
        t_file = TableauFileManager.open(filename=file)
        if isinstance(t_file, DatasourceFileInterface):
            for ds in t_file.datasources:
                # Perform operations on ds (TableauDatasource)
                pass
  5. Request JSON vs XML responses

    6.0.0

    While the library primarily works with ElementTree XML objects, you can request JSON responses from the Tableau Server.

    • XML (Default): Most methods return ElementTree.Element objects. This allows for powerful searching using XPath queries.
    • JSON: Methods derived from query_resource_json() return standard Python objects (dictionaries/lists) that map directly to JSON. This is useful for basic plural querying where filtering is available at the URL level.
  6. Manage and reuse Permissions objects

    6.0.0

    You can manage permissions for projects, workbooks, and datasources using Permissions objects. To avoid manual configuration, you can create a permissions object for a group or user and then reuse or transform it using copy methods.

    Reusing Permissions

    If you have a Permissions object and want to apply similar settings to a different group or user, use these methods on a PublishedContent instance (often a Project object):

    • PublishedContent.copy_permissions_obj_for_group(perms_obj, group_name_or_luid): Creates a new object for a different group.
    • PublishedContent.copy_permissions_obj_for_user(perms_obj, username_or_luid): Creates a new object for a specific user.

    Applying Permissions

    Use set_permissions or set_permissions_by_permissions_obj_list to apply these objects to a project or its defaults.

    # Create a base permissions object for a group
    best_group_perms_obj = proj.create_datasource_permissions_object_for_group('Best Group', role='Editor')
    
    # Reuse it for a second group
    second_best_group_perms_obj = proj.copy_permissions_obj_for_group(best_group_perms_obj, 'Second Best Group')
    
    # Transform it for a specific user
    my_user_perms_obj = proj.copy_permissions_obj_for_user(second_best_group_perms_obj, 'My User Name')
    
    # Apply the list of permissions to the project
    proj.clear_all_permissions()
    proj.set_permissiosn_by_permissions_obj_list([best_group_perms_obj, second_best_group_perms_obj, my_user_perms_obj])
  7. Understand the TableauServerRest object structure

    6.0.0

    The TableauServerRest object is the primary entry point for the library. It is a composite object that exposes various 'endpoint' methods (like .projects, .workbooks, .users, etc.) for interacting with Tableau Server.

    Key architectural details:

    • Endpoint Classes: Methods are organized into classes based on the Tableau REST API endpoint (e.g., GroupMethods, UserMethods). These classes do not represent data objects themselves but are collections of methods.
    • Inheritance: TableauServerRest inherits from TableauRestApiBase, which contains the core logic for connection management, basic REST API actions, and LUID lookups.
    • Endpoint Initialization: When you create a TableauServerRest instance, all sub-objects (endpoints) are instantiated and passed a reference to the main TableauServerRest object via self.rest. This allows endpoint methods to access shared connection details and base methods.
  8. Modify Tableau Datasources and Connections

    6.0.0

    The TableauDatasource class is the core of the library. It encapsulates a <datasource> XML element and provides access to its internal components:

    • TableauConnection: Represents the <connection> element. It contains properties related to the native Tableau connector. You can access raw XML attributes using connection.xml_obj.get('property-name') or set them using connection.xml_obj.set('property-name', 'value').
    • TableauColumn: Represents fields (either <col> or <column> elements). You can modify names, datatypes, and other properties. The TableauColumns container provides get_column_by_name() which searches both the name and the alias.
    • TableTableRelations: Encapsulates the original Tableau JOIN paradigm. Note that this does not support the newer Tableau 'Relationships' model introduced in version 2020.2.

    Important Implementation Detail: All component classes (TableauConnection, TableauColumn, etc.) hold an internal self.xml_obj that references a specific part of the parent TableauDatasource.xml object. Because these are all part of the same underlying ElementTree structure, changes made to a column or connection are automatically reflected in the parent datasource when it is saved.

  9. Understand TableauRestXml and TableauServerRest

    6.0.0
    The TableauRestXml class contains static methods and properties designed for use with any Tableau REST XML request or response. Because TableauServerRest inherits from TableauRestXml, you can call these utility methods directly on your TableauServerRest instance.
  10. How TableauServerRest classes work

    6.0.0

    In tableau_tools 6.0+, the tableau_rest_api sub-package uses TableauServerRest classes to organize methods into logical sub-objects (e.g., t.groups.create_group() instead of t.create_group()).

    Key behaviors:

    • Method Organization: Basic functionalities (like signin() or LUID lookups) remain on the base object, but most actions are grouped into sub-objects (e.g., projects, users, groups).
    • API Versioning: You can target specific Tableau Server API versions by instantiating versioned classes. For example, TableauServerRest311 targets API Version 3.11 (Tableau Server 2021.1).
    • Legacy Compatibility: Older versions (4.0 series) used TableauRestApiConnection, which placed all methods directly on the main object. Modern TableauServerRest objects are more organized but require using the correct sub-object.
    # Example: Using a specific API version (3.6 / 2019.4)
    t = TableauServerRest36(server="http://127.0.0.1", pat_name="my_pat", pat_secret="my_secret", site_content_url="my_site")
    
    # Accessing methods via sub-objects
    t.projects.update_project(project_id="...")
    
    # Basic methods remain on the base object
    t.signin()
  11. How tableau_documents manages Tableau files

    6.0.0

    The tableau_documents module is designed to modify existing Tableau XML files (TWB, TDS, TWBX, TDSX). It uses a factory pattern via TableauFileManager to return the appropriate object type based on the file extension.

    Key abstractions include:

    • DatasourceFileInterface: The primary entry point for XML modification, providing a .datasources() method that returns a list of TableauDatasource objects.
    • TableauXmlFile: Handles converting in-memory XML objects back into string XML for saving to disk via the .tableau_document property.
    • TableauPackagedFile: Manages ZIP-based files (TWBX, TDSX). It allows access to the internal XML via .tableau_xml_file and handles the complex process of repackaging files (including substituting new Hyper files) when saving.

    Note on Memory and Scope: To minimize memory usage, especially for large TWB files, the library only loads the <datasources> section into memory. Consequently, you can only modify datasource properties; you cannot access or change other XML elements in the workbook.

    from tableau_documents import TableauFileManager
    
    # TableauFileManager acts as a factory
    file_obj = TableauFileManager('path/to/my_workbook.twbx')
    
    # Access datasources via the DatasourceFileInterface
    for ds in file_obj.datasources():
        # Perform modifications
        pass
    
    file_obj.save_new_file('path/to/new_workbook.twbx')