def main():
    parser = argparse.ArgumentParser(description="Cancel all of the running background jobs.")
    # Common options; please keep those in sync across all samples
    parser.add_argument("--server", "-s", required=True, help="server address")
    parser.add_argument("--site", "-S", help="site name")
    parser.add_argument(
        "--token-name", "-p", required=True, help="name of the personal access token used to sign into the server"
    )
    parser.add_argument(
        "--token-value", "-v", required=True, help="value of the personal access token used to sign into the server"
    )
    parser.add_argument(
        "--logging-level",
        "-l",
        choices=["debug", "info", "error"],
        default="error",
        help="desired logging level (set to error by default)",
    )
    # Options specific to this sample
    # This sample has no additional options, yet. If you add some, please add them here

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        req = TSC.RequestOptions()

        req.filter.add(TSC.Filter("progress", TSC.RequestOptions.Operator.LessThanOrEqual, 0))
        for job in TSC.Pager(server.jobs, request_opts=req):
            print(server.jobs.cancel(job.id), job.id, job.status, job.type)
def automatically_create_users(users_to_import,
                               tableau_token_value='',
                               tableau_token_name='datadev',
                               tableau_content_url='chrishastieiwdev598367'):
    import tableauserverclient as tsc
    import getpass

    # Request user password if not provided already
    if tableau_token_value == '':
        import getpass
        tableau_token_value = getpass.getpass('Access token:')

    tableau_auth = tsc.PersonalAccessTokenAuth(tableau_token_name,
                                               tableau_token_value,
                                               tableau_content_url)
    server = tsc.Server('https://10ax.online.tableau.com/',
                        use_server_version=True)

    with server.auth.sign_in(tableau_auth):
        for user in users_to_import:
            group_item = check_if_group_exists(server, user['group'])
            if not group_item:
                new_group = tsc.GroupItem(user['group'])
                group_item = server.groups.create(new_group)

            user_item = check_if_user_exists(server, user['email'])
            if not user_item:
                new_user = tsc.UserItem(user['email'], 'Unlicensed')
                user_item = server.users.add(new_user)

            server.groups.add_user(group_item, user_item.id)
示例#3
0
def main():

    parser = argparse.ArgumentParser(description='Creates a sample user group.')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument('--token-name', '-p', required=True,
                        help='name of the personal access token used to sign into the server')
    parser.add_argument('--token-value', '-v', required=True,
                        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    # This sample has no additional options, yet. If you add some, please add them here

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        group = TSC.GroupItem('test')
        group = server.groups.create(group)
        print(group)
示例#4
0
def generate_report(view_name, filepath):
    # site_id = site to log into, do not specify for default site
    tableau_auth = TSC.PersonalAccessTokenAuth("Slack API Token",
                                               token,
                                               site_id="")
    server = TSC.Server(server_url, use_server_version=True)
    # The new endpoint was introduced in Version 2.5
    server.version = "2.5"

    with server.auth.sign_in(tableau_auth):
        # Query for the view that we want an image of
        req_option = TSC.RequestOptions()
        req_option.filter.add(
            TSC.Filter(TSC.RequestOptions.Field.Name,
                       TSC.RequestOptions.Operator.Equals, view_name))
        all_views, pagination_item = server.views.get(req_option)
        if not all_views:
            raise LookupError("View with the specified name was not found.")
        view_item = all_views[0]

        max_age = 1
        if not max_age:
            max_age = 1

        image_req_option = TSC.ImageRequestOptions(
            imageresolution=TSC.ImageRequestOptions.Resolution.High,
            maxage=max_age)
        server.views.populate_image(view_item, image_req_option)

        # Write file to local /tmp
        with open("/tmp/view_{0}.png".format(filepath), "wb") as image_file:
            image_file.write(view_item.image)
示例#5
0
def publish_to_server(site_name, server_address, project_name, tdsx_name,
                      tableau_token_name, tableau_token):
    '''Publishes updated, local .tdsx to Tableau, overwriting the original file.'''

    # Creates the auth object based on the config file.
    tableau_auth = TSC.PersonalAccessTokenAuth(
        token_name=tableau_token_name,
        personal_access_token=tableau_token,
        site_id=site_name)
    server = TSC.Server(server_address)
    print(f"Signing into to site: {site_name}.")

    # Signs in and find the specified project.
    with server.auth.sign_in(tableau_auth):
        all_projects, pagination_item = server.projects.get()
        for project in TSC.Pager(server.projects):
            if project.name == project_name:
                project_id = project.id
        if project_id == None:
            message = "Could not find project. Please update the config file."
            sys.exit(message)
        print(f"Publishing to {project_name}.")

        # Publishes the data source.
        overwrite_true = TSC.Server.PublishMode.Overwrite
        datasource = TSC.DatasourceItem(project_id)
        file_path = os.path.join(os.getcwd(), tdsx_name)
        datasource = server.datasources.publish(datasource, file_path,
                                                overwrite_true)
        print(f"Publishing of datasource '{tdsx_name}' complete.")
示例#6
0
 def test_sign_in_invalid_token(self):
     with open(SIGN_IN_ERROR_XML, 'rb') as f:
         response_xml = f.read().decode('utf-8')
     with requests_mock.mock() as m:
         m.post(self.baseurl + '/signin', text=response_xml, status_code=401)
         tableau_auth = TSC.PersonalAccessTokenAuth(token_name='mytoken', personal_access_token='invalid')
         self.assertRaises(TSC.ServerResponseError, self.server.auth.sign_in, tableau_auth)
示例#7
0
def publish_hyper():
    """
    Shows how to leverage the Tableau Server Client (TSC) to sign in and publish an extract directly to Tableau Online/Server
    """

    # Sign in to server
    tableau_auth = TSC.PersonalAccessTokenAuth(token_name=token_name, personal_access_token=token_value, site_id=site_name)
    server = TSC.Server(server_address, use_server_version=True)
    
    print(f"Signing into {site_name} at {server_address}")
    with server.auth.sign_in(tableau_auth):
        # Define publish mode - Overwrite, Append, or CreateNew
        publish_mode = TSC.Server.PublishMode.Overwrite
        
        # Get project_id from project_name
        all_projects, pagination_item = server.projects.get()
        for project in TSC.Pager(server.projects):
            if project.name == project_name:
                project_id = project.id
    
        # Create the datasource object with the project_id
        datasource = TSC.DatasourceItem(project_id)
        
        print(f"Publishing {hyper_name} to {project_name}...")
        # Publish datasource
        datasource = server.datasources.publish(datasource, path_to_hyper, publish_mode)
        print("Datasource published. Datasource ID: {0}".format(datasource.id))
示例#8
0
def main():
    parser = argparse.ArgumentParser(description='List out the names and LUIDs for different resource types.')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument('--token-name', '-n', required=True,
                        help='name of the personal access token used to sign into the server')
    parser.add_argument('--token-value', '-v', required=True,
                        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    parser.add_argument('resource_type', choices=['workbook', 'datasource', 'project', 'view', 'job', 'webhooks'])

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # Sign in to server
    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        endpoint = {
            'workbook': server.workbooks,
            'datasource': server.datasources,
            'view': server.views,
            'job': server.jobs,
            'project': server.projects,
            'webhooks': server.webhooks,
        }.get(args.resource_type)

        for resource in TSC.Pager(endpoint.get):
            print(resource.id, resource.name)
示例#9
0
def create_webhook(token, event_type):
    tableau_auth = TSC.PersonalAccessTokenAuth(token_name=TABLEAU_TOKEN_NAME,
                                               personal_access_token=token,
                                               site_id=TABLEAU_SITE_NAME)
    server = TSC.Server(TABLEAU_SERVER)

    # Set http options to disable verifying SSL
    server.add_http_options({'verify': False})
    server.use_server_version()
    with server.auth.sign_in_with_personal_access_token(tableau_auth):
        new_webhook = TSC.WebhookItem()
        new_webhook.name = "Webooks created from Heroku"
        new_webhook.url = HEROKU_URL
        new_webhook.event = event_type

        # Check if identical webhook is already created
        exists = False
        for existing_webhook in TSC.Pager(server.webhooks):
            exists = compare_webhook(new_webhook, existing_webhook)
            if exists:
                break

        if not exists:
            new_webhook = server.webhooks.create(new_webhook)
            print("Webhook created: {}".format(new_webhook))
            return True, new_webhook
        else:
            print("Webhook already exists: {}".format(new_webhook))
            return False, new_webhook
 def __init__(
     self,
     tableau_hostname,
     tableau_project,
     tableau_site_id=DEFAULT_SITE_ID,
     staging_bucket=None,
     tableau_token_name=None,
     tableau_token_secret=None,
     tableau_username=None,
     tableau_password=None,
 ):
     super().__init__()
     self.tableau_site_id = tableau_site_id
     self.tableau_hostname = tableau_hostname
     if tableau_token_name:
         self.tableau_auth = TSC.PersonalAccessTokenAuth(
             token_name=tableau_token_name,
             personal_access_token=tableau_token_secret,
             site_id="",
         )
     else:
         self.tableau_auth = TSC.TableauAuth(
             username=tableau_username,
             password=tableau_password,
             site_id=tableau_site_id,
         )
     self.tableau_server = TSC.Server(tableau_hostname,
                                      use_server_version=True)
     self.tableau_server.auth.sign_in(self.tableau_auth)
     self.tableau_project_name = tableau_project
     self.tableau_project_id = self._get_project_id(tableau_project)
     self.staging_bucket = staging_bucket
def main():

    parser = argparse.ArgumentParser(description='Demonstrate pagination on the list of workbooks on the server.')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument('--token-name', '-n', required=True,
                        help='name of the personal access token used to sign into the server')
    parser.add_argument('--token-value', '-v', required=True,
                        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    # This sample has no additional options, yet. If you add some, please add them here

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # Sign in to server
    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        # Pager returns a generator that yields one item at a time fetching
        # from Server only when necessary. Pager takes a server Endpoint as its
        # first parameter. It will call 'get' on that endpoint. To get workbooks
        # pass `server.workbooks`, to get users pass` server.users`, etc
        # You can then loop over the generator to get the objects one at a time
        # Here we print the workbook id for each workbook

        print("Your server contains the following workbooks:\n")
        for wb in TSC.Pager(server.workbooks):
            print(wb.name)
def main():
    parser = argparse.ArgumentParser(
        description=
        "Update a connection on a datasource or workbook to embed credentials")
    # Common options; please keep those in sync across all samples
    parser.add_argument("--server", "-s", required=True, help="server address")
    parser.add_argument("--site", "-S", help="site name")
    parser.add_argument(
        "--token-name",
        "-p",
        required=True,
        help="name of the personal access token used to sign into the server")
    parser.add_argument(
        "--token-value",
        "-v",
        required=True,
        help="value of the personal access token used to sign into the server")
    parser.add_argument(
        "--logging-level",
        "-l",
        choices=["debug", "info", "error"],
        default="error",
        help="desired logging level (set to error by default)",
    )
    # Options specific to this sample
    parser.add_argument("resource_type", choices=["workbook", "datasource"])
    parser.add_argument("resource_id")
    parser.add_argument("connection_id")
    parser.add_argument("datasource_username")
    parser.add_argument("datasource_password")

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name,
                                               args.token_value,
                                               site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        endpoint = {
            "workbook": server.workbooks,
            "datasource": server.datasources
        }.get(args.resource_type)

        update_function = endpoint.update_connection
        resource = endpoint.get_by_id(args.resource_id)
        endpoint.populate_connections(resource)
        connections = list(
            filter(lambda x: x.id == args.connection_id, resource.connections))
        assert len(connections) == 1
        connection = connections[0]
        connection.username = args.datasource_username
        connection.password = args.datasource_password
        connection.embed_password = True
        print(update_function(resource, connection).__dict__)
示例#13
0
def main():
    parser = argparse.ArgumentParser(
        description='List out the names and LUIDs for different resource types.'
    )
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument(
        '--site',
        '-S',
        default="",
        help='site to log into, do not specify for default site')
    parser.add_argument('--token-name',
                        '-n',
                        required=True,
                        help='username to signin under')
    parser.add_argument('--token',
                        '-t',
                        help='personal access token for logging in')

    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')

    parser.add_argument('resource_type',
                        choices=[
                            'workbook', 'datasource', 'project', 'view', 'job',
                            'webhooks'
                        ])

    args = parser.parse_args()
    token = os.environ.get('TOKEN', args.token)
    if not token:
        print("--token or TOKEN environment variable needs to be set")
        sys.exit(1)

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # SIGN IN
    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name,
                                               token,
                                               site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        endpoint = {
            'workbook': server.workbooks,
            'datasource': server.datasources,
            'view': server.views,
            'job': server.jobs,
            'project': server.projects,
            'webhooks': server.webhooks,
        }.get(args.resource_type)

        for resource in TSC.Pager(endpoint.get):
            print(resource.id, resource.name)
def main():
    parser = argparse.ArgumentParser(
        description=
        'Update a connection on a datasource or workbook to embed credentials')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument(
        '--token-name',
        '-p',
        required=True,
        help='name of the personal access token used to sign into the server')
    parser.add_argument(
        '--token-value',
        '-v',
        required=True,
        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    parser.add_argument('resource_type', choices=['workbook', 'datasource'])
    parser.add_argument('resource_id')
    parser.add_argument('connection_id')
    parser.add_argument('datasource_username')
    parser.add_argument('datasource_password')

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name,
                                               args.token_value,
                                               site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        endpoint = {
            'workbook': server.workbooks,
            'datasource': server.datasources
        }.get(args.resource_type)

        update_function = endpoint.update_connection
        resource = endpoint.get_by_id(args.resource_id)
        endpoint.populate_connections(resource)
        connections = list(
            filter(lambda x: x.id == args.connection_id, resource.connections))
        assert (len(connections) == 1)
        connection = connections[0]
        connection.username = args.datasource_username
        connection.password = args.datasource_password
        connection.embed_password = True
        print(update_function(resource, connection).__dict__)
示例#15
0
def main():
    parser = argparse.ArgumentParser(description='Logs in to the server.')
    # This command is special, as it doesn't take `token-value` and it offer both token-based and password based authentication.
    # Please still try to keep common options like `server` and `site` consistent across samples
    # Common options:
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--username',
                       '-u',
                       help='username to sign into the server')
    group.add_argument(
        '--token-name',
        '-n',
        help='name of the personal access token used to sign into the server')

    args = parser.parse_args()

    # Set logging level based on user input, or error by default.
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # Make sure we use an updated version of the rest apis.
    server = TSC.Server(args.server, use_server_version=True)

    if args.username:
        # Trying to authenticate using username and password.
        password = getpass.getpass("Password: "******"\nSigning in...\nServer: {}\nSite: {}\nUsername: {}".format(
            args.server, args.site, args.username))
        tableau_auth = TSC.TableauAuth(args.username,
                                       password,
                                       site_id=args.site)
        with server.auth.sign_in(tableau_auth):
            print('Logged in successfully')

    else:
        # Trying to authenticate using personal access tokens.
        personal_access_token = getpass.getpass("Personal Access Token: ")

        print("\nSigning in...\nServer: {}\nSite: {}\nToken name: {}".format(
            args.server, args.site, args.token_name))
        tableau_auth = TSC.PersonalAccessTokenAuth(
            token_name=args.token_name,
            personal_access_token=personal_access_token,
            site_id=args.site)
        with server.auth.sign_in_with_personal_access_token(tableau_auth):
            print('Logged in successfully')
示例#16
0
def delete_webhook(token, id):
    tableau_auth = TSC.PersonalAccessTokenAuth(token_name=TABLEAU_TOKEN_NAME,
                                               personal_access_token=token,
                                               site_id=TABLEAU_SITE_NAME)
    server = TSC.Server(TABLEAU_SERVER)

    # Set http options to disable verifying SSL
    server.add_http_options({'verify': False})
    server.use_server_version()
    with server.auth.sign_in_with_personal_access_token(tableau_auth):
        server.webhooks.delete(id)
示例#17
0
def connectToTab(servadd, tokname, token):
    if (servadd is None) or (tokname is None) or (token is None):
        print('missing values')
        return
    else:
        server = TSC.Server(servadd, use_server_version=True)
        tableau_auth = TSC.PersonalAccessTokenAuth(token_name=tokname,
                                                personal_access_token=token, site_id='dataforgedev786186')
        with server.auth.sign_in_with_personal_access_token(tableau_auth):
            print('Logged in successfully')
            return
示例#18
0
    def test_sign_in_with_personal_access_tokens(self):
        with open(SIGN_IN_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.post(self.baseurl + '/signin', text=response_xml)
            tableau_auth = TSC.PersonalAccessTokenAuth(token_name='mytoken',
                                                       personal_access_token='Random123Generated', site_id='Samples')
            self.server.auth.sign_in(tableau_auth)

        self.assertEqual('eIX6mvFsqyansa4KqEI1UwOpS8ggRs2l', self.server.auth_token)
        self.assertEqual('6b7179ba-b82b-4f0f-91ed-812074ac5da6', self.server.site_id)
        self.assertEqual('1a96d216-e9b8-497b-a82a-0b899a965e01', self.server.user_id)
示例#19
0
def main():

    parser = argparse.ArgumentParser(description='Explore webhook functions supported by the Server API.')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument('--token-name', '-p', required=True,
                        help='name of the personal access token used to sign into the server')
    parser.add_argument('--token-value', '-v', required=True,
                        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    parser.add_argument('--create', help='create a webhook')
    parser.add_argument('--delete', help='delete a webhook', action='store_true')

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # SIGN IN
    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):

        # Create webhook if create flag is set (-create, -c)
        if args.create:

            new_webhook = TSC.WebhookItem()
            new_webhook.name = args.create
            new_webhook.url = "https://ifttt.com/maker-url"
            new_webhook.event = "datasource-created"
            print(new_webhook)
            new_webhook = server.webhooks.create(new_webhook)
            print("Webhook created. ID: {}".format(new_webhook.id))

        # Gets all webhook items
        all_webhooks, pagination_item = server.webhooks.get()
        print("\nThere are {} webhooks on site: ".format(pagination_item.total_available))
        print([webhook.name for webhook in all_webhooks])

        if all_webhooks:
            # Pick one webhook from the list and delete it
            sample_webhook = all_webhooks[0]
            # sample_webhook.delete()
            print("+++"+sample_webhook.name)

            if (args.delete):
                print("Deleting webhook " + sample_webhook.name)
                server.webhooks.delete(sample_webhook.id)
示例#20
0
def main():
    parser = argparse.ArgumentParser(description='Delete the `Europe` region from a published `World Indicators` datasource.')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument('--token-name', '-p', required=True,
                        help='name of the personal access token used to sign into the server')
    parser.add_argument('--token-value', '-v', required=True,
                        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    parser.add_argument('datasource_id', help="The LUID of the `World Indicators` datasource")

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        # We use a unique `request_id` for every request.
        # In case the submission of the update job fails, we won't know wether the job was submitted
        # or not. It could be that the server received the request, changed the data, but then the
        # network connection broke down.
        # If you want to have a way to retry, e.g., inserts while making sure they aren't duplicated,
        # you need to use `request_id` for that purpose.
        # In our case, we don't care about retries. And the delete is idempotent anyway.
        # Hence, we simply use a randomly generated request id.
        request_id = str(uuid.uuid4())

        # This action will delete all rows with `Region=Europe` from the published data source.
        # Other actions (inserts, updates, ...) are also available. For more information see
        # https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_how_to_update_data_to_hyper.htm
        actions = [
            {
                "action": "delete",
                "target-table": "Extract",
                "target-schema": "Extract",
                "condition": {"op": "eq", "target-col": "Region", "const": {"type": "string", "v": "Europe"}}
            }
        ]

        job = server.datasources.update_hyper_data(args.datasource_id, request_id=request_id, actions=actions)

        print(f"Update job posted (ID: {job.id})")
        print("Waiting for job...")
        # `wait_for_job` will throw if the job isn't executed successfully
        job = server.jobs.wait_for_job(job)
        print("Job finished succesfully")
示例#21
0
def main():
    parser = argparse.ArgumentParser(
        description='Export to PDF all of the views in a workbook.')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument(
        '--token-name',
        '-p',
        required=True,
        help='name of the personal access token used to sign into the server')
    parser.add_argument(
        '--token-value',
        '-v',
        required=True,
        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    parser.add_argument('--file',
                        '-f',
                        default='out.pdf',
                        help='filename to store the exported data')
    parser.add_argument('resource_id', help='LUID for the workbook')

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tempdir = tempfile.mkdtemp('tsc')
    logging.debug("Saving to tempdir: %s", tempdir)

    try:
        tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name,
                                                   args.token_value,
                                                   site_id=args.site)
        server = TSC.Server(args.server, use_server_version=True)
        with server.auth.sign_in(tableau_auth):
            get_list = functools.partial(get_views_for_workbook, server)
            download = functools.partial(download_pdf, server, tempdir)

            downloaded = (download(x) for x in get_list(args.resource_id))
            output = reduce(combine_into, downloaded, PyPDF2.PdfFileMerger())
            with file(args.file, 'wb') as f:
                output.write(f)
    finally:
        cleanup(tempdir)
示例#22
0
def main():

    parser = argparse.ArgumentParser(
        description=
        'List workbooks on site, with option set to ignore SSL verification.')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument(
        '--token-name',
        '-p',
        required=True,
        help='name of the personal access token used to sign into the server')
    parser.add_argument(
        '--token-value',
        '-v',
        required=True,
        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    # This sample has no additional options, yet. If you add some, please add them here

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # Step 1: Create required objects for sign in
    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name,
                                               args.token_value,
                                               site_id=args.site)
    server = TSC.Server(args.server)

    # Step 2: Set http options to disable verifying SSL
    server.add_http_options({'verify': False})

    with server.auth.sign_in(tableau_auth):

        # Step 3: Query all workbooks and list them
        all_workbooks, pagination_item = server.workbooks.get()
        print('{0} workbooks found. Showing {1}:'.format(
            pagination_item.total_available, pagination_item.page_size))
        for workbook in all_workbooks:
            print('\t{0} (ID: {1})'.format(workbook.name, workbook.id))
def main():

    parser = argparse.ArgumentParser(description="Move one workbook from the default project to another.")
    # Common options; please keep those in sync across all samples
    parser.add_argument("--server", "-s", required=True, help="server address")
    parser.add_argument("--site", "-S", help="site name")
    parser.add_argument(
        "--token-name", "-p", required=True, help="name of the personal access token used to sign into the server"
    )
    parser.add_argument(
        "--token-value", "-v", required=True, help="value of the personal access token used to sign into the server"
    )
    parser.add_argument(
        "--logging-level",
        "-l",
        choices=["debug", "info", "error"],
        default="error",
        help="desired logging level (set to error by default)",
    )
    # Options specific to this sample
    parser.add_argument("--workbook-name", "-w", required=True, help="name of workbook to move")
    parser.add_argument("--destination-project", "-d", required=True, help="name of project to move workbook into")

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # Step 1: Sign in to server
    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        # Step 2: Find destination project
        try:
            dest_project = server.projects.filter(name=urllib.parse.quote_plus(args.destination_project))[0]
        except IndexError:
            raise LookupError(f"No project named {args.destination_project} found.")

        # Step 3: Query workbook to move
        try:
            workbook = server.workbooks.filter(name=urllib.parse.quote_plus(args.workbook_name))[0]
        except IndexError:
            raise LookupError(f"No workbook named {args.workbook_name} found")

        # Step 4: Update workbook with new project id
        workbook.project_id = dest_project.id
        target_workbook = server.workbooks.update(workbook)
        print(f"New project: {target_workbook.project_name}")
示例#24
0
def main():
    parser = argparse.ArgumentParser(description="Trigger a refresh task on a workbook or datasource.")
    # Common options; please keep those in sync across all samples
    parser.add_argument("--server", "-s", required=True, help="server address")
    parser.add_argument("--site", "-S", help="site name")
    parser.add_argument(
        "--token-name", "-p", required=True, help="name of the personal access token used to sign into the server"
    )
    parser.add_argument(
        "--token-value", "-v", required=True, help="value of the personal access token used to sign into the server"
    )
    parser.add_argument(
        "--logging-level",
        "-l",
        choices=["debug", "info", "error"],
        default="error",
        help="desired logging level (set to error by default)",
    )
    # Options specific to this sample
    parser.add_argument("resource_type", choices=["workbook", "datasource"])
    parser.add_argument("resource_id")

    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        if args.resource_type == "workbook":
            # Get the workbook by its Id to make sure it exists
            resource = server.workbooks.get_by_id(args.resource_id)

            # trigger the refresh, you'll get a job id back which can be used to poll for when the refresh is done
            job = server.workbooks.refresh(args.resource_id)
        else:
            # Get the datasource by its Id to make sure it exists
            resource = server.datasources.get_by_id(args.resource_id)

            # trigger the refresh, you'll get a job id back which can be used to poll for when the refresh is done
            job = server.datasources.refresh(resource)

        print(f"Update job posted (ID: {job.id})")
        print("Waiting for job...")
        # `wait_for_job` will throw if the job isn't executed successfully
        job = server.jobs.wait_for_job(job)
        print("Job finished succesfully")
示例#25
0
def get_webhooks(token):
    tableau_auth = TSC.PersonalAccessTokenAuth(token_name=TABLEAU_TOKEN_NAME,
                                               personal_access_token=token,
                                               site_id=TABLEAU_SITE_NAME)
    server = TSC.Server(TABLEAU_SERVER)

    # Set http options to disable verifying SSL
    server.add_http_options({'verify': False})
    server.use_server_version()
    with server.auth.sign_in_with_personal_access_token(tableau_auth):
        webhooks = []
        for webhook in TSC.Pager(server.webhooks):
            webhooks.append(webhook)

    return webhooks
示例#26
0
def main():
    parser = argparse.ArgumentParser(description='Use the metadata API to get information on a published data source.')
    # Common options; please keep those in sync across all samples
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--site', '-S', help='site name')
    parser.add_argument('--token-name', '-n', required=True,
                        help='name of the personal access token used to sign into the server')
    parser.add_argument('--token-value', '-v', required=True,
                        help='value of the personal access token used to sign into the server')
    parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
                        help='desired logging level (set to error by default)')
    # Options specific to this sample
    parser.add_argument('datasource_name', nargs='?', help="The name of the published datasource. If not present, we query all data sources.")


    args = parser.parse_args()

    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # Sign in to server
    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        # Execute the query
        result = server.metadata.query("""
            query useMetadataApiToQueryOrdersDatabases($name: String){
                publishedDatasources (filter: {name: $name}) {
                    luid
                    name
                    description
                    projectName
                    fields {
                        name
                    }
                }
            }""", {"name": args.datasource_name})

        # Display warnings/errors (if any)
        if result.get("errors"):
            print("### Errors/Warnings:")
            pprint(result["errors"])
        
        # Print the results
        if result.get("data"):
            print("### Results:")
            pprint(result["data"]["publishedDatasources"])
def run(args):
    # Set logging level based on user input, or error by default
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # Step 1: Sign in to server.
    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)
    server = TSC.Server(args.server, use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        if args.workbook:
            item = get_workbook_by_name(server, args.workbook)
        else:
            item = get_datasource_by_name(server, args.datasource)
        schedule = get_schedule_by_name(server, args.schedule)

        assign_to_schedule(server, item, schedule)
示例#28
0
    def test_sign_in_with_personal_access_tokens(self):
        with open(SIGN_IN_XML, "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.post(self.baseurl + "/signin", text=response_xml)
            tableau_auth = TSC.PersonalAccessTokenAuth(
                token_name="mytoken",
                personal_access_token="Random123Generated",
                site_id="Samples")
            self.server.auth.sign_in(tableau_auth)

        self.assertEqual("eIX6mvFsqyansa4KqEI1UwOpS8ggRs2l",
                         self.server.auth_token)
        self.assertEqual("6b7179ba-b82b-4f0f-91ed-812074ac5da6",
                         self.server.site_id)
        self.assertEqual("1a96d216-e9b8-497b-a82a-0b899a965e01",
                         self.server.user_id)
示例#29
0
def main():
    parser = argparse.ArgumentParser(description='Logs in to the server.')

    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')

    parser.add_argument('--server', '-s', required=True, help='server address')

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--username',
                       '-u',
                       help='username to sign into the server')
    group.add_argument(
        '--token-name',
        '-n',
        help='name of the personal access token used to sign into the server')
    parser.add_argument('--sitename', '-S', default=None)

    args = parser.parse_args()

    # Set logging level based on user input, or error by default.
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # Make sure we use an updated version of the rest apis.
    server = TSC.Server(args.server, use_server_version=True)

    if args.username:
        # Trying to authenticate using username and password.
        password = getpass.getpass("Password: "******"Personal Access Token: ")
        tableau_auth = TSC.PersonalAccessTokenAuth(
            token_name=args.token_name,
            personal_access_token=personal_access_token,
            site_id=args.sitename)
        with server.auth.sign_in_with_personal_access_token(tableau_auth):
            print('Logged in successfully')
示例#30
0
def main():

    query = """
    {
        fields{
            name
        }
    }
    """

    parser = argparse.ArgumentParser(description='Logs in to the server.')

    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')

    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument(
        '--token-name',
        '-n',
        help='name of the personal access token used to sign into the server')
    parser.add_argument('--token', '-t', help='personal token')
    parser.add_argument('--sitename', '-S', default=None)

    args = parser.parse_args()

    # Set logging level based on user input, or error by default.
    logging_level = getattr(logging, args.logging_level.upper())
    logging.basicConfig(level=logging_level)

    # Make sure we use an updated version of the rest apis.
    server = TSC.Server(args.server, use_server_version=True)
    tableau_auth = TSC.PersonalAccessTokenAuth(
        token_name=args.token_name,
        personal_access_token=args.token,
        site_id=args.sitename)
    with server.auth.sign_in_with_personal_access_token(tableau_auth):
        print('Logged in successfully')
        workbooks, pagination_item = server.workbooks.get()
        resp = server.metadata.query(query)
        datasources = resp['data']
        datasource = pd.json_normalize(datasources, max_level=1)
        print(datasource)