### Install tableauserverclient Source: https://context7.com/tableau/server-client-python/llms.txt Install the library using pip. ```bash pip install tableauserverclient ``` -------------------------------- ### Install Twine for PyPI Publishing Source: https://github.com/tableau/server-client-python/wiki/Release-a-new-version Use pip to install the twine package, which is required for publishing the new release to PyPI. This command is typically run in the master branch. ```bash pip install twine ``` -------------------------------- ### Manage Tableau Prep Flows Source: https://context7.com/tableau/server-client-python/llms.txt Provides examples for publishing, running, populating connections, downloading, and deleting Tableau Prep flows. Requires authentication and a project ID for publishing. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all flows ──────────────────────────────────────────────────── flows, pagination = server.flows.get() print(f"Total flows: {pagination.total_available}") # ── Publish a flow ──────────────────────────────────────────────────── new_flow = TSC.FlowItem(project_id="proj-uuid-here", name="Clean Orders") published_flow = server.flows.publish( new_flow, "/local/path/clean_orders.tflx", TSC.Server.PublishMode.Overwrite, ) print(f"Published flow ID: {published_flow.id}") # ── Run a flow (returns a job) ──────────────────────────────────────── run_job = server.flows.refresh(published_flow) finished = server.jobs.wait_for_job(run_job) print(f"Flow run finished: {finished.status}") # ── Populate connections ────────────────────────────────────────────── server.flows.populate_connections(published_flow) for conn in published_flow.connections: print(f" {conn.connection_type}") # ── Download ────────────────────────────────────────────────────────── path = server.flows.download(published_flow.id, filepath="/tmp/") # ── Delete ──────────────────────────────────────────────────────────── server.flows.delete(published_flow.id) ``` -------------------------------- ### Initialize Tableau Server Client and Authenticate Source: https://context7.com/tableau/server-client-python/llms.txt Initializes the Tableau Server client and authenticates using personal access tokens. This setup is required before performing server operations. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): print("Sign in successful") ``` -------------------------------- ### Manage Tableau Datasources with Python Source: https://context7.com/tableau/server-client-python/llms.txt Use this snippet to perform various operations on Tableau datasources, including listing, getting, publishing, downloading, refreshing, updating credentials, and deleting. Ensure you have the tableauserverclient library installed and valid authentication credentials. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all datasources ────────────────────────────────────────────── datasources, pagination = server.datasources.get() print(f"Total datasources: {pagination.total_available}") # ── Get a single datasource ─────────────────────────────────────────── ds = server.datasources.get_by_id("ds-uuid-here") print(f"Datasource: {ds.name}, certified: {ds.certified}") # ── Publish a datasource ────────────────────────────────────────────── new_ds = TSC.DatasourceItem(project_id="proj-uuid-here", name="Orders DB") conn_creds = TSC.ConnectionCredentials("db_user", "db_pass", embed=True, oauth=False) published_ds = server.datasources.publish( new_ds, "/local/path/orders.tdsx", TSC.Server.PublishMode.Overwrite, connection_credentials=conn_creds, ) print(f"Published datasource ID: {published_ds.id}") # ── Async publish (file > 64 MB is auto-chunked) ────────────────────── job = server.datasources.publish( new_ds, "/local/path/big_data.tdsx", TSC.Server.PublishMode.Overwrite, as_job=True, ) server.jobs.wait_for_job(job) # ── Download a datasource ───────────────────────────────────────────── path = server.datasources.download(published_ds.id, filepath="/tmp/") print(f"Downloaded to: {path}") # ── Refresh extract ──────────────────────────────────────────────────── refresh_job = server.datasources.refresh(published_ds) server.jobs.wait_for_job(refresh_job) # ── Populate connections ─────────────────────────────────────────────── server.datasources.populate_connections(published_ds) for conn in published_ds.connections: print(f" {conn.connection_type} → {conn.server_address}:{conn.server_port}") # ── Update connection credentials ────────────────────────────────────── conn = published_ds.connections[0] conn.username = "new_db_user" conn.password = "new_db_pass" conn.embed_password = True server.datasources.update_connection(published_ds, conn) # ── Delete ───────────────────────────────────────────────────────────── server.datasources.delete(published_ds.id) ``` -------------------------------- ### Manage Groups with Tableau Server Client Source: https://context7.com/tableau/server-client-python/llms.txt Provides examples for managing groups on a Tableau site, including listing, creating local and Active Directory groups, modifying group membership, and filtering groups. Requires server authentication. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all groups ─────────────────────────────────────────────────── groups, pagination = server.groups.get() for g in groups: print(f" {g.id} {g.name}") # ── Create a local group ────────────────────────────────────────────── new_group = TSC.GroupItem("SALES NORTHWEST") new_group.minimum_site_role = TSC.UserItem.Role.ExplorerCanPublish new_group = server.groups.create(new_group) print(f"Created group: {new_group.id}") # ── Create an Active Directory group ───────────────────────────────── ad_group = TSC.GroupItem("DOMAIN\SalesTeam") ad_group.domain_name = "example.com" ad_group.minimum_site_role = TSC.UserItem.Role.Explorer ad_group.license_mode = TSC.GroupItem.LicenseMode.onSync server.groups.create_AD_group(ad_group) # ── Add/remove single users ────────────────────────────────────────── user_id = "user-uuid-here" server.groups.add_user(new_group, user_id) server.groups.remove_user(new_group, user_id) # ── Add/remove multiple users (API 3.21+) ──────────────────────────── all_users = list(TSC.Pager(server.users)) server.groups.add_users(new_group, all_users[:5]) server.groups.remove_users(new_group, all_users[:5]) # ── Populate users in a group ───────────────────────────────────────── server.groups.populate_users(new_group) for user in new_group.users: print(f" {user.name}") # ── Django-style filter ────────────────────────────────────────────── sales_groups = list(server.groups.filter(name__like="SALES").order_by("name")) print([g.name for g in sales_groups]) # ── Delete a group ──────────────────────────────────────────────────── server.groups.delete(new_group.id) ``` -------------------------------- ### Monitor and Cancel Tableau Server Jobs Source: https://context7.com/tableau/server-client-python/llms.txt Shows how to list, retrieve, and wait for background jobs like extract refreshes and flow runs. Includes examples for triggering a refresh and cancelling a job. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all background jobs ────────────────────────────────────────── jobs, pagination = server.jobs.get() for j in jobs: print(f" {j.id} type={j.type} status={j.status}") # ── Get a specific job ──────────────────────────────────────────────── job = server.jobs.get_by_id("job-uuid-here") print(f"Job status: {job.status} progress: {job.progress}") # ── Trigger a refresh and wait for it ───────────────────────────────── ds = server.datasources.get_by_id("ds-uuid-here") refresh_job = server.datasources.refresh(ds) try: finished = server.jobs.wait_for_job(refresh_job, timeout=300) print(f"Refresh complete. Status: {finished.status}") except TSC.JobFailedException as e: print(f"Refresh failed: {e}") except TSC.JobCancelledException as e: print(f"Refresh cancelled: {e}") # ── Cancel a running job ────────────────────────────────────────────── server.jobs.cancel(refresh_job.id) ``` -------------------------------- ### Define Interval Items for Schedules with Python Source: https://context7.com/tableau/server-client-python/llms.txt Define recurrence intervals for schedules and subscriptions using classes like HourlyInterval. This example shows how to set up an hourly interval that runs every 2 hours between 8 AM and 6 PM. ```python import tableauserverclient as TSC # ── Hourly interval (every 2 hours, 8am–6pm) ───────────────────────────────── hourly = TSC.HourlyInterval( start_time="08:00:00", end_time="18:00:00", interval_value=2, # every 2 hours ) ``` -------------------------------- ### Manage Tableau Server Webhooks Source: https://context7.com/tableau/server-client-python/llms.txt Create, list, get, test, and delete webhooks for event-driven automation. Ensure you have the necessary permissions to manage webhooks on your Tableau Server. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── Create a webhook ────────────────────────────────────────────────── new_webhook = TSC.WebhookItem() new_webhook.name = "Notify on workbook publish" new_webhook.url = "https://hooks.example.com/tableau-events" new_webhook.event = "webhook-source-event-datasource-created" created = server.webhooks.create(new_webhook) print(f"Created webhook ID: {created.id}") # ── List all webhooks ───────────────────────────────────────────────── all_hooks, _ = server.webhooks.get() for hook in all_hooks: print(f" {hook.id} {hook.name} event={hook.event}") # ── Get a single webhook ────────────────────────────────────────────── hook = server.webhooks.get_by_id(created.id) # ── Test a webhook ──────────────────────────────────────────────────── test_result = server.webhooks.test(created.id) print(f"Test HTTP status: {test_result.status_code}") # ── Delete a webhook ────────────────────────────────────────────────── server.webhooks.delete(created.id) ``` -------------------------------- ### Export Tableau Views to Various Formats with Python Source: https://context7.com/tableau/server-client-python/llms.txt This snippet demonstrates how to export Tableau views as PNG images, PDFs, CSV files, and Excel files. It also shows how to retrieve view usage statistics and preview thumbnails. Ensure the tableauserverclient library is installed and you are authenticated. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all views (with usage stats) ──────────────────────────────── views, pagination = server.views.get(usage=True) print(f"Total views: {pagination.total_available}") for v in views[:5]: print(f" {v.name} total_views={v.total_views}") # ── Get a single view by ID ─────────────────────────────────────────── view = server.views.get_by_id("view-uuid-here") # ── Export view as PNG image ────────────────────────────────────────── img_opts = TSC.ImageRequestOptions(imageresolution=TSC.ImageRequestOptions.Resolution.High) server.views.populate_image(view, img_opts) with open(f"/tmp/{view.name}.png", "wb") as f: f.write(view.image) # ── Export view as PDF ──────────────────────────────────────────────── pdf_opts = TSC.PDFRequestOptions( page_type=TSC.PDFRequestOptions.PageType.Letter, orientation=TSC.PDFRequestOptions.Orientation.Portrait, maxage=1, ) server.views.populate_pdf(view, pdf_opts) with open(f"/tmp/{view.name}.pdf", "wb") as f: f.write(view.pdf) # ── Export view data as CSV ─────────────────────────────────────────── csv_opts = TSC.CSVRequestOptions(maxage=1) server.views.populate_csv(view, csv_opts) with open(f"/tmp/{view.name}.csv", "wb") as f: for chunk in view.csv: f.write(chunk) # ── Export view as Excel ────────────────────────────────────────────── excel_opts = TSC.ExcelRequestOptions(maxage=5) server.views.populate_excel(view, excel_opts) with open(f"/tmp/{view.name}.xlsx", "wb") as f: f.write(view.excel) # ── Preview thumbnail ───────────────────────────────────────────────── server.views.populate_preview_image(view) with open(f"/tmp/{view.name}_thumb.png", "wb") as f: f.write(view.preview_image) ``` -------------------------------- ### Tasks Endpoint Source: https://context7.com/tableau/server-client-python/llms.txt Provides functionality to query and run extract refresh tasks associated with schedules. Includes methods to list all tasks, get a task by ID, run a task immediately, and delete a task. ```APIDOC ## `server.tasks` — Tasks Endpoint Query and run extract refresh tasks associated with schedules. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all extract refresh tasks ──────────────────────────────────── tasks, pagination = server.tasks.get() for task in tasks: print(f" {task.id} type={task.task_type} schedule_id={task.schedule_id}") # ── Get a task by ID ────────────────────────────────────────────────── task = server.tasks.get_by_id("task-uuid-here") # ── Run a task immediately ──────────────────────────────────────────── job = server.tasks.run_now(task) finished = server.jobs.wait_for_job(job) print(f"Task completed with status: {finished.status}") # ── Delete a task ───────────────────────────────────────────────────── server.tasks.delete(task.id) ``` ``` -------------------------------- ### Get a single workbook Source: https://context7.com/tableau/server-client-python/llms.txt Retrieves a specific workbook by its ID. ```APIDOC ## GET /workbooks/{workbook_id} ### Description Retrieves a specific workbook by its ID. ### Method GET ### Endpoint /api/3.10/sites/{site_id}/workbooks/{workbook_id} ### Parameters #### Path Parameters - **workbook_id** (string) - Required - The ID of the workbook to retrieve. ### Response #### Success Response (200) - **workbook** (object) - A WorkbookItem object representing the requested workbook. ### Response Example { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "name": "Sales Dashboard", "project_name": "Default" } ``` -------------------------------- ### Server Object Initialization Source: https://context7.com/tableau/server-client-python/llms.txt Illustrates how to create and configure the `TSC.Server` object, which represents the connection to a Tableau Server or Tableau Cloud instance. It covers basic construction, automatic version detection, disabling SSL verification, and setting a specific API version. ```APIDOC ## Server Object Initialization The `TSC.Server` object is the central point for interacting with Tableau Server or Tableau Cloud. All other resources (workbooks, users, sites, etc.) are accessed as attributes of this object. ### Basic Construction ```python import tableauserverclient as TSC # Basic construction — version defaults to REST API 2.4 server = TSC.Server("https://my-tableau-server.com") ``` ### Auto-Detect Server Version To automatically detect and use the highest REST API version supported by the server: ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) ``` ### Disable SSL Verification For development or testing environments, you can disable SSL verification. **Note:** This is not recommended for production use. ```python import tableauserverclient as TSC server = TSC.Server( "https://my-tableau-server.com", use_server_version=True, http_options={"verify": False}, ) ``` ### Pinning a Specific API Version To use a specific REST API version: ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com") server.version = "3.15" ``` ### Version Negotiation Helpers Inspect and assert server API versions: ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com") # ... sign in ... print(server.check_at_least_version("3.10")) # Returns True or False server.assert_at_least_version("3.5", "Custom views") # Raises an exception if the server version is older than 3.5 ``` ### Inspecting Server Info After Sign-in After signing in, you can retrieve server information: ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "") with server.auth.sign_in(auth): info = server.server_info.get() print(f"Product version : {info.product_version}") print(f"REST API version: {info.rest_api_version}") print(f"Build number : {info.build_number}") ``` ``` -------------------------------- ### Get a Single Workbook by ID Source: https://context7.com/tableau/server-client-python/llms.txt Fetches a specific workbook from Tableau Server using its unique ID. ```python wb = server.workbooks.get_by_id("a1b2c3d4-e5f6-7890-abcd-ef1234567890") ``` -------------------------------- ### Sign In, Sign Out, and Switch Sites Source: https://context7.com/tableau/server-client-python/llms.txt Manage authentication state on a Tableau Server. The `sign_in` method returns a context manager for automatic sign-out. `switch_site` allows changing sites without re-authenticating. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", site_id="Sales") # Context manager — sign out happens automatically with server.auth.sign_in(auth): all_wb, _ = server.workbooks.get() print(f"Found {len(all_wb)} workbooks") # Switch to another site without re-authenticating target_site = server.sites.get_by_name("Marketing") with server.auth.switch_site(target_site): mkt_wb, _ = server.workbooks.get() print(f"Marketing site has {len(mkt_wb)} workbooks") # Back on Sales site here ``` -------------------------------- ### Filtering and Sorting with RequestOptions Source: https://context7.com/tableau/server-client-python/llms.txt Demonstrates how to apply server-side filtering and sorting to list endpoints using the `RequestOptions` class. This includes exact matches, multiple value filtering (IN operator), combining filters with sorting, and using a Django-style queryset API. ```APIDOC ## `RequestOptions`, `Filter`, `Sort` — Filtering and Sorting Apply server-side filtering and sorting to any list endpoint. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── Filter workbooks by name (exact match) ──────────────────────────── opts = TSC.RequestOptions() opts.filter.add( TSC.Filter(TSC.RequestOptions.Field.Name, TSC.RequestOptions.Operator.Equals, "Sales Dashboard") ) results, _ = server.workbooks.get(opts) # ── Filter by multiple values (IN operator) ─────────────────────────── opts2 = TSC.RequestOptions() opts2.filter.add( TSC.Filter( TSC.RequestOptions.Field.Name, TSC.RequestOptions.Operator.In, ["Sales Dashboard", "Finance Report", "KPI Overview"], ) ) # ── Combine filter + sort ───────────────────────────────────────────── opts3 = TSC.RequestOptions(pagesize=50) opts3.filter.add( TSC.Filter(TSC.RequestOptions.Field.Name, TSC.RequestOptions.Operator.Has, "Sales") ) opts3.sort.add( TSC.Sort(TSC.RequestOptions.Field.Name, TSC.RequestOptions.Direction.Asc) ) wbs, pagination = server.workbooks.get(opts3) print(f"Found {pagination.total_available} workbooks matching 'Sales'") # ── Django-style queryset API ───────────────────────────────────────── # filter(field=value), filter(field__operator=value), order_by("field") sales_wbs = list(server.workbooks.filter(name__has="Sales").order_by("name")) print([wb.name for wb in sales_wbs]) # Supported operators: eq, gt, gte, lt, lte, in, has, like, cieq (case-insensitive eq) recent_users = list( server.users.filter(site_role="Explorer").order_by("-name") ) ``` ``` -------------------------------- ### Create Daily, Weekly, and Monthly Intervals for Schedules Source: https://context7.com/tableau/server-client-python/llms.txt Define different interval types for scheduling tasks. Ensure the `start_time` is in HH:MM:SS format. ```python import tableauserverclient as TSC # Daily interval (every day at 6am) daily = TSC.DailyInterval(start_time="06:00:00") # Weekly interval (Mon and Thu at midnight) weekly = TSC.WeeklyInterval( start_time="00:00:00", interval_values=["Monday", "Thursday"], ) # Monthly interval (1st of each month at 3am) monthly = TSC.MonthlyInterval(start_time="03:00:00", interval_value=1) ``` -------------------------------- ### Sign In, Sign Out, and Switch Site Source: https://context7.com/tableau/server-client-python/llms.txt Details on how to sign in to, sign out of, or switch between sites on a Tableau Server using the `server.auth` object. It highlights the use of context managers for automatic sign-out and site switching. ```APIDOC ## `server.auth.sign_in` / `sign_out` / `switch_site` These methods manage the authentication state and site context for interacting with Tableau Server. ### Sign In and Sign Out (Context Manager) The `sign_in` method can be used as a context manager, ensuring that the user is automatically signed out upon exiting the `with` block. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", site_id="Sales") with server.auth.sign_in(auth): # Perform operations on the server, e.g., get workbooks all_wb, _ = server.workbooks.get() print(f"Found {len(all_wb)} workbooks on the Sales site.") # Automatically signed out here ``` ### Switching Sites The `switch_site` method allows you to change the current site context without needing to re-authenticate, provided you are already signed in. It also functions as a context manager. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", site_id="Sales") with server.auth.sign_in(auth): print(f"Currently on site: {server.site_id}") # Get the target site object target_site = server.sites.get_by_name("Marketing") # Switch to the Marketing site using a context manager with server.auth.switch_site(target_site): print(f"Switched to site: {server.site_id}") mkt_wb, _ = server.workbooks.get() print(f"Found {len(mkt_wb)} workbooks on the Marketing site.") # Automatically switched back to the original site (Sales) here print(f"Back on site: {server.site_id}") ``` ``` -------------------------------- ### Manage Subscriptions with Python Source: https://context7.com/tableau/server-client-python/llms.txt Create, list, update, and delete email subscriptions for views and workbooks. Ensure you have authenticated with the server before performing these operations. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all subscriptions ──────────────────────────────────────────── subscriptions, _ = server.subscriptions.get() for s in subscriptions: print(f" {s.id} subject={s.subject} user_id={s.user_id}") # ── Create a subscription ───────────────────────────────────────────── views, _ = server.views.get() schedules, _ = server.schedules.get() subscription_schedule = next( (s for s in schedules if s.schedule_type == TSC.ScheduleItem.Type.Subscription), None ) new_sub = TSC.SubscriptionItem( subject="Weekly KPI Update", schedule_id=subscription_schedule.id, user_id=server.user_id, target=TSC.Target(views[0].id, "view"), ) created = server.subscriptions.create(new_sub) print(f"Created subscription: {created.id}") # ── Update a subscription ───────────────────────────────────────────── created.subject = "Daily KPI Update" server.subscriptions.update(created) # ── Delete a subscription ───────────────────────────────────────────── server.subscriptions.delete(created.id) ``` -------------------------------- ### Create a Schedule with a Daily Interval Source: https://context7.com/tableau/server-client-python/llms.txt Create a new schedule on Tableau Server using a defined interval. Requires authentication and operates within a signed-in context. ```python server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): schedule = TSC.ScheduleItem( name="Nightly Refresh", priority=50, schedule_type=TSC.ScheduleItem.Type.Extract, execution_order=TSC.ScheduleItem.ExecutionOrder.Parallel, interval_item=daily, ) created = server.schedules.create(schedule) print(f"Schedule created: {created.id}") ``` -------------------------------- ### Favorites Endpoint Source: https://context7.com/tableau/server-client-python/llms.txt Enables users to manage their favorites list by adding and removing content such as workbooks, datasources, views, and projects. Includes methods for getting a user's favorites and adding/deleting specific content types. ```APIDOC ## `server.favorites` — Favorites Endpoint Add and remove content from a user's favorites list. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): user_id = server.user_id # ── Get a user's favorites ──────────────────────────────────────────── server.favorites.get(server.users.get_by_id(user_id)) # ── Add a workbook to favorites ─────────────────────────────────────── wb = server.workbooks.get_by_id("wb-uuid-here") server.favorites.add_workbook(wb, user_id) # ── Add a datasource to favorites ───────────────────────────────────── ds = server.datasources.get_by_id("ds-uuid-here") server.favorites.add_datasource(ds, user_id) # ── Add a view to favorites ─────────────────────────────────────────── views, _ = server.views.get() server.favorites.add_view(views[0], user_id) # ── Add a project to favorites ──────────────────────────────────────── projects, _ = server.projects.get() server.favorites.add_project(projects[0], user_id) # ── Remove from favorites ───────────────────────────────────────────── server.favorites.delete_workbook(wb, user_id) server.favorites.delete_datasource(ds, user_id) ``` ``` -------------------------------- ### Manage Users with Tableau Server Client Source: https://context7.com/tableau/server-client-python/llms.txt Demonstrates common operations for managing users on a Tableau site, including listing, retrieving, creating, updating, and removing users. Ensure you have authenticated with the server before executing these commands. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all users ──────────────────────────────────────────────────── users, pagination = server.users.get() print(f"Total users: {pagination.total_available}") print([u.name for u in users]) # ── Get a single user by ID ────────────────────────────────────────── user = server.users.get_by_id("user-uuid-here") print(f"Name: {user.name}, Role: {user.site_role}, Email: {user.email}") # ── Create (add) a new user ────────────────────────────────────────── new_user = TSC.UserItem(name="jsmith", site_role=TSC.UserItem.Role.Explorer) new_user.email = "jsmith@example.com" new_user.fullname = "John Smith" new_user.auth_setting = TSC.UserItem.Auth.SAML created = server.users.add(new_user) print(f"Created user ID: {created.id}") # ── Update a user ───────────────────────────────────────────────────── created.site_role = TSC.UserItem.Role.SiteAdministratorExplorer updated = server.users.update(created) print(f"Updated role: {updated.site_role}") # ── Remove a user from the site ─────────────────────────────────────── server.users.remove(created.id) # ── Get workbooks for a user ────────────────────────────────────────── wbs, _ = server.users.get_workbooks_for_user(user.id) print([wb.name for wb in wbs]) # ── Get groups a user belongs to ───────────────────────────────────── groups, _ = server.users.get_groups_for_user(user.id) print([g.name for g in groups]) ``` -------------------------------- ### Manage Tableau Server Sites with Python Source: https://context7.com/tableau/server-client-python/llms.txt This snippet demonstrates how to manage Tableau Server sites, including listing, creating, updating, and deleting them. This functionality requires server administrator privileges. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "") # default site with server.auth.sign_in(auth): # ── List all sites ──────────────────────────────────────────────────── sites, pagination = server.sites.get() for site in sites: print(f" {site.id} {site.name} contentUrl={site.content_url} state={site.state}") # ── Get current site ────────────────────────────────────────────────── current = server.sites.get_by_id(server.site_id) print(f"Current site: {current.name}") # ── Get site by name ────────────────────────────────────────────────── sales_site = server.sites.get_by_name("Sales") # ── Create a site ───────────────────────────────────────────────────── new_site = TSC.SiteItem( name="NewDivision", content_url="newdivision", admin_mode=TSC.SiteItem.AdminMode.ContentAndUsers, ) new_site.storage_quota = 1000 # MB new_site.user_quota = 50 created_site = server.sites.create(new_site) print(f"Created site ID: {created_site.id}") # ── Update a site ───────────────────────────────────────────────────── created_site.name = "New Division" server.sites.update(created_site) # ── Delete a site ───────────────────────────────────────────────────── server.sites.delete(created_site.id) ``` -------------------------------- ### Manage Tasks with server.tasks Source: https://context7.com/tableau/server-client-python/llms.txt Query, run, and delete extract refresh tasks associated with schedules. Use get_by_id to retrieve a specific task and wait_for_job to monitor its completion. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all extract refresh tasks ──────────────────────────────────── tasks, pagination = server.tasks.get() for task in tasks: print(f" {task.id} type={task.task_type} schedule_id={task.schedule_id}") # ── Get a task by ID ────────────────────────────────────────────────── task = server.tasks.get_by_id("task-uuid-here") # ── Run a task immediately ──────────────────────────────────────────── job = server.tasks.run_now(task) finished = server.jobs.wait_for_job(job) print(f"Task completed with status: {finished.status}") # ── Delete a task ───────────────────────────────────────────────────── server.tasks.delete(task.id) ``` -------------------------------- ### Authentication Methods Source: https://context7.com/tableau/server-client-python/llms.txt Demonstrates how to use different authentication mechanisms: username/password, Personal Access Tokens, and JSON Web Tokens with the TSC library. Authentication objects can be used with the `server.auth.sign_in()` method or as context managers for automatic sign-out. ```APIDOC ## Authentication Methods Three credential classes allow for different authentication mechanisms: * `TSC.TableauAuth`: For username and password authentication. * `TSC.PersonalAccessTokenAuth`: For authentication using Personal Access Tokens (recommended for automation). * `TSC.JWTAuth`: For authentication using JSON Web Tokens. All authentication classes can be used with `server.auth.sign_in()` and as context managers for automatic sign-out. ### Username / Password Authentication ```python import tableauserverclient as TSC tableau_auth = TSC.TableauAuth( username="admin", password="s3cr3t", site_id="MarketingTeam", # Use an empty string "" for the default site user_id_to_impersonate=None, # Optional: impersonate another user ) ``` ### Personal Access Token Authentication ```python import tableauserverclient as TSC pat_auth = TSC.PersonalAccessTokenAuth( token_name="my-automation-token", personal_access_token="AbCdEfGhIjKlMnOpQrStUvWx", site_id="MarketingTeam", ) ``` ### JSON Web Token Authentication ```python import tableauserverclient as TSC import jwt as pyjwt encoded = pyjwt.encode({"sub": "user@example.com", "aud": "tableau"}, "secret", algorithm="HS256") jwt_auth = TSC.JWTAuth(jwt=encoded, site_id="MarketingTeam") ``` ### Using Authentication with Context Manager ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "") with server.auth.sign_in(auth): print("Signed in as user:", server.user_id) print("Site ID: ", server.site_id) print("Auth token: ", server.auth_token[:8], "...") # Automatically signed out here ``` ``` -------------------------------- ### Manage Tableau Server Schedules Source: https://context7.com/tableau/server-client-python/llms.txt Demonstrates listing, creating, updating, and deleting extract refresh and subscription schedules. Requires authentication with a personal access token. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all schedules ──────────────────────────────────────────────── schedules, pagination = server.schedules.get() for s in schedules: print(f" {s.name} type={s.schedule_type} frequency={s.execution_order}") # ── Create a daily schedule ─────────────────────────────────────────── hourly_interval = TSC.HourlyInterval(start_time="07:00:00", end_time="23:00:00", interval_value=4) new_schedule = TSC.ScheduleItem( name="Refresh every 4 hours", priority=50, schedule_type=TSC.ScheduleItem.Type.Extract, execution_order=TSC.ScheduleItem.ExecutionOrder.Parallel, interval_item=hourly_interval, ) created_schedule = server.schedules.create(new_schedule) print(f"Created schedule ID: {created_schedule.id}") # ── Add a workbook to a schedule ────────────────────────────────────── wb = server.workbooks.get_by_id("wb-uuid-here") server.workbooks.populate_views(wb) response = server.schedules.add_to_schedule(created_schedule.id, workbook=wb) print(f"Added to schedule: {response.result}") # ── Add a datasource to a schedule ──────────────────────────────────── ds = server.datasources.get_by_id("ds-uuid-here") server.schedules.add_to_schedule(created_schedule.id, datasource=ds) # ── Update a schedule ───────────────────────────────────────────────── created_schedule.priority = 75 server.schedules.update(created_schedule) # ── Delete a schedule ───────────────────────────────────────────────── server.schedules.delete(created_schedule.id) ``` -------------------------------- ### Projects Endpoint Source: https://context7.com/tableau/server-client-python/llms.txt Manage projects and their default permissions. This includes listing, creating, updating, and deleting projects. ```APIDOC ## `server.projects` — Projects Endpoint Manage projects and their default permissions. ### Usage ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # List all projects projects, pagination = server.projects.get() default_project = next((p for p in projects if p.is_default()), None) print(f"Default project: {default_project.name} id={default_project.id}") # Create a project new_proj = TSC.ProjectItem( name="Analytics Hub", description="Shared analytics content", content_permissions=TSC.ProjectItem.ContentPermissions.ManagedByOwner, ) new_proj = server.projects.create(new_proj) print(f"Created project ID: {new_proj.id}") # Create a nested (child) project child_proj = TSC.ProjectItem(name="Finance", parent_id=new_proj.id) child_proj = server.projects.create(child_proj) # Update a project new_proj.description = "All public dashboards" server.projects.update(new_proj) # Filter projects by name req_opts = TSC.RequestOptions() req_opts.filter.add( TSC.Filter(TSC.RequestOptions.Field.Name, TSC.RequestOptions.Operator.Equals, "Analytics Hub") ) matching, _ = server.projects.get(req_opts) # Delete a project server.projects.delete(child_proj.id) server.projects.delete(new_proj.id) ``` ``` -------------------------------- ### Populate Workbook Views Source: https://context7.com/tableau/server-client-python/llms.txt Fetches and populates the views associated with a workbook object. ```python server.workbooks.populate_views(published) for view in published.views: print(f" View: {view.name}") ``` -------------------------------- ### Populate Workbook Connections Source: https://context7.com/tableau/server-client-python/llms.txt Fetches and populates the data connections associated with a workbook object. ```python server.workbooks.populate_connections(published) for conn in published.connections: print(f" Connection: {conn.datasource_name} @ {conn.server_address}") ``` -------------------------------- ### Download a workbook Source: https://context7.com/tableau/server-client-python/llms.txt Downloads a workbook from Tableau Server. ```APIDOC ## GET /workbooks/{workbook_id}/content ### Description Downloads the content of a specific workbook. ### Method GET ### Endpoint /api/3.10/sites/{site_id}/workbooks/{workbook_id}/content ### Parameters #### Path Parameters - **workbook_id** (string) - Required - The ID of the workbook to download. ### Response #### Success Response (200) - **content** (file) - The binary content of the workbook file (.twb or .twbx). ### Response Example (Binary content of the workbook file) ``` -------------------------------- ### Download a Workbook Source: https://context7.com/tableau/server-client-python/llms.txt Downloads a specified workbook from Tableau Server to a local file path. ```python path = server.workbooks.download(published.id, filepath="/tmp/") print(f"Downloaded to: {path}") ``` -------------------------------- ### Manage Data Alerts with Python Source: https://context7.com/tableau/server-client-python/llms.txt Query and manage data-driven alerts for views, including listing, retrieving, updating, and deleting alerts, as well as managing user subscriptions to alerts. Requires server authentication. ```python import tableauserverclient as TSC server = TSC.Server("https://my-tableau-server.com", use_server_version=True) auth = TSC.PersonalAccessTokenAuth("token_name", "token_secret", "default") with server.auth.sign_in(auth): # ── List all data alerts ────────────────────────────────────────────── alerts, _ = server.data_alerts.get() for alert in alerts: print(f" {alert.id} subject={alert.subject} owner_id={alert.owner_id}") # ── Get a single alert ──────────────────────────────────────────────── alert = server.data_alerts.get_by_id("alert-uuid-here") # ── Add a user to an alert ──────────────────────────────────────────── server.data_alerts.add_user_to_alert(alert, "user-uuid-here") # ── Delete a user from an alert ─────────────────────────────────────── server.data_alerts.delete_user_from_alert(alert, "user-uuid-here") # ── Update an alert ─────────────────────────────────────────────────── alert.subject = "Alert: Revenue below target" server.data_alerts.update(alert) # ── Delete an alert ─────────────────────────────────────────────────── server.data_alerts.delete(alert.id) ``` -------------------------------- ### Handle Failed Sign-in Errors Source: https://context7.com/tableau/server-client-python/llms.txt Catch `FailedSignInError` when authentication credentials are invalid. Ensure correct username and password are used. ```python import tableauserverclient as TSC from tableauserverclient import ServerResponseError, NotSignedInError, FailedSignInError server = TSC.Server("https://my-tableau-server.com", use_server_version=True) # Failed sign-in try: auth = TSC.TableauAuth("admin", "wrong_password") server.auth.sign_in(auth) except FailedSignInError as e: print(f"Sign-in failed: {e}") ``` -------------------------------- ### Export Workbook as PDF Source: https://context7.com/tableau/server-client-python/llms.txt Exports a workbook as a PDF file with specified options for page size and orientation. The PDF content is available in the `published.pdf` attribute. ```python pdf_opts = TSC.PDFRequestOptions(page_type=TSC.PDFRequestOptions.PageType.A4, orientation=TSC.PDFRequestOptions.Orientation.Landscape) server.workbooks.populate_pdf(published, pdf_opts) with open("/tmp/workbook.pdf", "wb") as f: f.write(published.pdf) ``` -------------------------------- ### Export Workbook as PowerPoint Source: https://context7.com/tableau/server-client-python/llms.txt Exports a workbook as a PowerPoint presentation. The presentation content is available in the `published.powerpoint` attribute. ```python server.workbooks.populate_powerpoint(published) with open("/tmp/workbook.pptx", "wb") as f: f.write(published.powerpoint) ```