示例#1
0
    def test_populate_views_with_usage(self):
        with open(POPULATE_VIEWS_USAGE_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.get(
                self.baseurl +
                '/1f951daf-4061-451a-9df1-69a8062664f2/views?includeUsageStatistics=true',
                text=response_xml)
            single_workbook = TSC.WorkbookItem('test')
            single_workbook._id = '1f951daf-4061-451a-9df1-69a8062664f2'
            self.server.workbooks.populate_views(single_workbook, usage=True)

            views_list = single_workbook.views
            self.assertEqual('097dbe13-de89-445f-b2c3-02f28bd010c1',
                             views_list[0].id)
            self.assertEqual(2, views_list[0].total_views)
            self.assertEqual('2c1ab9d7-8d64-4cc6-b495-52e40c60c330',
                             views_list[1].id)
            self.assertEqual(37, views_list[1].total_views)
            self.assertEqual('0599c28c-6d82-457e-a453-e52c1bdb00f5',
                             views_list[2].id)
            self.assertEqual(0, views_list[2].total_views)
    def test_update(self):
        with open(UPDATE_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.put(self.baseurl + '/1f951daf-4061-451a-9df1-69a8062664f2', text=response_xml)
            single_workbook = TSC.WorkbookItem('1d0304cd-3796-429f-b815-7258370b9b74', show_tabs=True)
            single_workbook._id = '1f951daf-4061-451a-9df1-69a8062664f2'
            single_workbook.owner_id = 'dd2239f6-ddf1-4107-981a-4cf94e415794'
            single_workbook.name = 'renamedWorkbook'
            single_workbook.data_acceleration_config = {'acceleration_enabled': True,
                                                        'accelerate_now': False,
                                                        'last_updated_at': None,
                                                        'acceleration_status': None}
            single_workbook = self.server.workbooks.update(single_workbook)

        self.assertEqual('1f951daf-4061-451a-9df1-69a8062664f2', single_workbook.id)
        self.assertEqual(True, single_workbook.show_tabs)
        self.assertEqual('1d0304cd-3796-429f-b815-7258370b9b74', single_workbook.project_id)
        self.assertEqual('dd2239f6-ddf1-4107-981a-4cf94e415794', single_workbook.owner_id)
        self.assertEqual('renamedWorkbook', single_workbook.name)
        self.assertEqual(True, single_workbook.data_acceleration_config['acceleration_enabled'])
        self.assertEqual(False, single_workbook.data_acceleration_config['accelerate_now'])
    def test_publish_with_hidden_view(self):
        with open(PUBLISH_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.post(self.baseurl, text=response_xml)

            new_workbook = TSC.WorkbookItem(name='Sample',
                                            show_tabs=False,
                                            project_id='ee8c6e70-43b6-11e6-af4f-f7b0d8e20760')

            sample_workbook = os.path.join(TEST_ASSET_DIR, 'SampleWB.twbx')
            publish_mode = self.server.PublishMode.CreateNew

            new_workbook = self.server.workbooks.publish(new_workbook,
                                                         sample_workbook,
                                                         publish_mode,
                                                         hidden_views=['GDP per capita'])

            request_body = m._adapter.request_history[0]._request.body
            # order of attributes in xml is unspecified
            self.assertTrue(re.search(rb'<views><view.*?hidden=\"true\".*?\/><\/views>', request_body))
            self.assertTrue(re.search(rb'<views><view.*?name=\"GDP per capita\".*?\/><\/views>', request_body))
    def test_publish(self):
        with open(PUBLISH_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.post(self.baseurl, text=response_xml)

            new_workbook = TSC.WorkbookItem(
                name='Sample',
                show_tabs=False,
                project_id='ee8c6e70-43b6-11e6-af4f-f7b0d8e20760')

            sample_workbook = os.path.join(TEST_ASSET_DIR, 'SampleWB.twbx')
            publish_mode = self.server.PublishMode.CreateNew

            new_workbook = self.server.workbooks.publish(
                new_workbook, sample_workbook, publish_mode)

        self.assertEqual('a8076ca1-e9d8-495e-bae6-c684dbb55836',
                         new_workbook.id)
        self.assertEqual('RESTAPISample', new_workbook.name)
        self.assertEqual('Sample Description', new_workbook.description)
        self.assertEqual('RESTAPISample_0', new_workbook.content_url)
        self.assertEqual(False, new_workbook.show_tabs)
        self.assertEqual(1, new_workbook.size)
        self.assertEqual('2016-08-18T18:33:24Z',
                         format_datetime(new_workbook.created_at))
        self.assertEqual('2016-08-18T20:31:34Z',
                         format_datetime(new_workbook.updated_at))
        self.assertEqual('ee8c6e70-43b6-11e6-af4f-f7b0d8e20760',
                         new_workbook.project_id)
        self.assertEqual('default', new_workbook.project_name)
        self.assertEqual('5de011f8-5aa9-4d5b-b991-f462c8dd6bb7',
                         new_workbook.owner_id)
        self.assertEqual('fe0b4e89-73f4-435e-952d-3a263fbfa56c',
                         new_workbook.views[0].id)
        self.assertEqual('GDP per capita', new_workbook.views[0].name)
        self.assertEqual('RESTAPISample_0/sheets/GDPpercapita',
                         new_workbook.views[0].content_url)
示例#5
0
    def test_add_permissions(self) -> None:
        with open(UPDATE_PERMISSIONS, "rb") as f:
            response_xml = f.read().decode("utf-8")

        single_workbook = TSC.WorkbookItem("test")
        single_workbook._id = "21778de4-b7b9-44bc-a599-1506a2639ace"

        bob = UserItem.as_reference("7c37ee24-c4b1-42b6-a154-eaeab7ee330a")
        group_of_people = GroupItem.as_reference("5e5e1978-71fa-11e4-87dd-7382f5c437af")

        new_permissions = [PermissionsRule(bob, {"Write": "Allow"}), PermissionsRule(group_of_people, {"Read": "Deny"})]

        with requests_mock.mock() as m:
            m.put(self.baseurl + "/21778de4-b7b9-44bc-a599-1506a2639ace/permissions", text=response_xml)
            permissions = self.server.workbooks.update_permissions(single_workbook, new_permissions)

        self.assertEqual(permissions[0].grantee.tag_name, "group")
        self.assertEqual(permissions[0].grantee.id, "5e5e1978-71fa-11e4-87dd-7382f5c437af")
        self.assertDictEqual(permissions[0].capabilities, {TSC.Permission.Capability.Read: TSC.Permission.Mode.Deny})

        self.assertEqual(permissions[1].grantee.tag_name, "user")
        self.assertEqual(permissions[1].grantee.id, "7c37ee24-c4b1-42b6-a154-eaeab7ee330a")
        self.assertDictEqual(permissions[1].capabilities, {TSC.Permission.Capability.Write: TSC.Permission.Mode.Allow})
    def test_publish_async(self):
        with open(PUBLISH_ASYNC_XML, 'rb') as f:
            response_xml = f.read().decode('utf-8')
        with requests_mock.mock() as m:
            m.post(self.baseurl, text=response_xml)

            new_workbook = TSC.WorkbookItem(name='Sample',
                                            show_tabs=False,
                                            project_id='ee8c6e70-43b6-11e6-af4f-f7b0d8e20760')

            sample_workbook = os.path.join(TEST_ASSET_DIR, 'SampleWB.twbx')
            publish_mode = self.server.PublishMode.CreateNew

            new_job = self.server.workbooks.publish(new_workbook,
                                                    sample_workbook,
                                                    publish_mode,
                                                    as_job=True)

        self.assertEqual('7c3d599e-949f-44c3-94a1-f30ba85757e4', new_job.id)
        self.assertEqual('PublishWorkbook', new_job.type)
        self.assertEqual('0', new_job.progress)
        self.assertEqual('2018-06-29T23:22:32Z', format_datetime(new_job.created_at))
        self.assertEqual('1', new_job.finish_code)
示例#7
0
def main():

    parser = argparse.ArgumentParser(description='Publish a workbook to server.')
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--username', '-u', required=True, help='username to sign into server')
    parser.add_argument('--filepath', '-f', required=True, help='filepath to the workbook to publish')
    parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
                        help='desired logging level (set to error by default)')

    args = parser.parse_args()

    password = getpass.getpass("Password: "******"Workbook published. ID: {0}".format(new_workbook.id))
        else:
            error = "The default project could not be found."
            raise LookupError(error)
示例#8
0
    def run_command(args):
        logger = log(__class__.__name__, args.logging_level)
        logger.debug(_("tabcmd.launching"))
        session = Session()
        server = session.create_session(args)

        if args.project_name:
            try:
                project_id = Server.get_project_by_name_and_parent_path(
                    logger, server, args.project_name, args.parent_project_path
                )
            except Exception as exc:
                Errors.exit_with_error(logger, _("publish.errors.server_resource_not_found"), exc)
        else:
            project_id = ""
            args.project_name = "default"
            args.parent_project_path = ""

        publish_mode = PublishCommand.get_publish_mode(args)

        source = PublishCommand.get_filename_extension_if_tableau_type(logger, args.filename)
        logger.info(_("publish.status").format(args.filename))
        if source in ["twbx", "twb"]:
            new_workbook = TSC.WorkbookItem(project_id, name=args.name, show_tabs=args.tabbed)
            try:
                new_workbook = server.workbooks.publish(new_workbook, args.filename, publish_mode)
            except IOError as ioe:
                Errors.exit_with_error(logger, ioe)
            logger.info(_("publish.success") + "\n{}".format(new_workbook.webpage_url))

        elif source in ["tds", "tdsx", "hyper"]:
            new_datasource = TSC.DatasourceItem(project_id, name=args.name)
            try:
                new_datasource = server.datasources.publish(new_datasource, args.filename, publish_mode)
            except IOError as ioe:
                Errors.exit_with_error(logger, exc)
            logger.info(_("publish.success") + "\n{}".format(new_datasource.webpage_url))
示例#9
0
    def test_update(self) -> None:
        with open(UPDATE_XML, "rb") as f:
            response_xml = f.read().decode("utf-8")
        with requests_mock.mock() as m:
            m.put(self.baseurl + "/1f951daf-4061-451a-9df1-69a8062664f2", text=response_xml)
            single_workbook = TSC.WorkbookItem("1d0304cd-3796-429f-b815-7258370b9b74", show_tabs=True)
            single_workbook._id = "1f951daf-4061-451a-9df1-69a8062664f2"
            single_workbook.owner_id = "dd2239f6-ddf1-4107-981a-4cf94e415794"
            single_workbook.name = "renamedWorkbook"
            single_workbook.data_acceleration_config = {
                "acceleration_enabled": True,
                "accelerate_now": False,
                "last_updated_at": None,
                "acceleration_status": None,
            }
            single_workbook = self.server.workbooks.update(single_workbook)

        self.assertEqual("1f951daf-4061-451a-9df1-69a8062664f2", single_workbook.id)
        self.assertEqual(True, single_workbook.show_tabs)
        self.assertEqual("1d0304cd-3796-429f-b815-7258370b9b74", single_workbook.project_id)
        self.assertEqual("dd2239f6-ddf1-4107-981a-4cf94e415794", single_workbook.owner_id)
        self.assertEqual("renamedWorkbook", single_workbook.name)
        self.assertEqual(True, single_workbook.data_acceleration_config["acceleration_enabled"])
        self.assertEqual(False, single_workbook.data_acceleration_config["accelerate_now"])
    def test_add_permissions(self):
        with open(UPDATE_PERMISSIONS, 'rb') as f:
            response_xml = f.read().decode('utf-8')

        single_workbook = TSC.WorkbookItem('test')
        single_workbook._id = '21778de4-b7b9-44bc-a599-1506a2639ace'

        bob = UserItem.as_reference("7c37ee24-c4b1-42b6-a154-eaeab7ee330a")
        group_of_people = GroupItem.as_reference(
            "5e5e1978-71fa-11e4-87dd-7382f5c437af")

        new_permissions = [
            PermissionsRule(bob, {'Write': 'Allow'}),
            PermissionsRule(group_of_people, {'Read': 'Deny'})
        ]

        with requests_mock.mock() as m:
            m.put(self.baseurl +
                  "/21778de4-b7b9-44bc-a599-1506a2639ace/permissions",
                  text=response_xml)
            permissions = self.server.workbooks.update_permissions(
                single_workbook, new_permissions)

        self.assertEqual(permissions[0].grantee.tag_name, 'group')
        self.assertEqual(permissions[0].grantee.id,
                         '5e5e1978-71fa-11e4-87dd-7382f5c437af')
        self.assertDictEqual(
            permissions[0].capabilities,
            {TSC.Permission.Capability.Read: TSC.Permission.Mode.Deny})

        self.assertEqual(permissions[1].grantee.tag_name, 'user')
        self.assertEqual(permissions[1].grantee.id,
                         '7c37ee24-c4b1-42b6-a154-eaeab7ee330a')
        self.assertDictEqual(
            permissions[1].capabilities,
            {TSC.Permission.Capability.Write: TSC.Permission.Mode.Allow})
 def test_populate_preview_image_missing_id(self):
     single_workbook = TSC.WorkbookItem('test')
     self.assertRaises(TSC.MissingRequiredFieldError,
                       self.server.workbooks.populate_preview_image,
                       single_workbook)
 def test_populate_connections_missing_id(self):
     single_workbook = TSC.WorkbookItem('test')
     self.assertRaises(TSC.MissingRequiredFieldError,
                       self.server.workbooks.populate_connections,
                       single_workbook)
 def test_update_missing_id(self):
     single_workbook = TSC.WorkbookItem('test')
     self.assertRaises(TSC.MissingRequiredFieldError, self.server.workbooks.update, single_workbook)
示例#14
0
        with server.auth.sign_in(tableau_auth):
            user = TSC.UserItem(server_username[i], 'SiteAdministrator')
            user = server.users.add(user)
            user = server.users.update(user, 'password')

#Getting the default project and publishing workbook and datasource###
    project_id = ''
    time.sleep(1)
    with server.auth.sign_in(tableau_auth):
        all_projects, pagination_item = server.projects.get()
        for project in all_projects:

            if project.name == 'Default':
                project_id = project.id

    new_workbook = TSC.WorkbookItem(project_id)
    new_datasource = TSC.DatasourceItem(project_id)
    credentials = TSC.ConnectionCredentials(db_username[i],
                                            db_password[i],
                                            embed=True)

    with server.auth.sign_in(tableau_auth):
        server.datasources.publish(new_datasource, uniqueField[i] + ".tdsx",
                                   TSC.Server.PublishMode.Overwrite,
                                   credentials)
        server.workbooks.publish(new_workbook, uniqueField[i] + ".twbx",
                                 TSC.Server.PublishMode.Overwrite, credentials)

    site_check = 0

# print "The workbook connections have been updated. Please open the newly created workbook to test."
示例#15
0
        # Step 2: Get all the projects on server, then look for the default one.
        all_projects, pagination_item = server.projects.get()
        default_project = next((project for project in all_projects if project.is_default()), None)

        connection1 = ConnectionItem()
        connection1.server_address = "mssql.test.com"
        connection1.connection_credentials = ConnectionCredentials("test", "password", True)

        connection2 = ConnectionItem()
        connection2.server_address = "postgres.test.com"
        connection2.server_port = "5432"
        connection2.connection_credentials = ConnectionCredentials("test", "password", True)

        all_connections = list()
        all_connections.append(connection1)
        all_connections.append(connection2)

        # Step 3: If default project is found, form a new workbook item and publish.
        if default_project is not None:
            new_workbook = TSC.WorkbookItem(default_project.id)

            new_job = server.workbooks.publish(new_workbook, args.workbookpath, overwrite_true,
                                                           connections=all_connections, as_job= True,
                                                           skip_connection_check=True)
            print("Workbook published. JOB ID: {0}".format(new_job.id))

        else:
            error = "The default project could not be found."
            raise LookupError(error)
def main():

    parser = argparse.ArgumentParser(description="Move one workbook from the"
                                     "default project of the default site to"
                                     "the default project of another site.")
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--username',
                        '-u',
                        required=True,
                        help='username to sign into server')
    parser.add_argument('--workbook-name',
                        '-w',
                        required=True,
                        help='name of workbook to move')
    parser.add_argument('--destination-site',
                        '-d',
                        required=True,
                        help='name of site to move workbook into')
    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')

    args = parser.parse_args()

    password = getpass.getpass("Password: "******"No site named {} found.".format(
                        args.destination_site)
                    raise LookupError(error)

                tableau_auth.site_id = args.destination_site

                # Signing into another site requires another server object
                # because of the different auth token and site ID.
                with dest_server.auth.sign_in(tableau_auth):

                    # Step 5: Create a new workbook item and publish workbook. Note that
                    # an empty project_id will publish to the 'Default' project.
                    new_workbook = TSC.WorkbookItem(name=args.workbook_name,
                                                    project_id="")
                    new_workbook = dest_server.workbooks.publish(
                        new_workbook,
                        workbook_path,
                        mode=TSC.Server.PublishMode.Overwrite)
                    print("Successfully moved {0} ({1})".format(
                        new_workbook.name, new_workbook.id))

                # Step 6: Delete workbook from source site and delete temp directory
                source_server.workbooks.delete(all_workbooks[0].id)

            finally:
                shutil.rmtree(tmpdir)
 def test_publish_invalid_file_type(self):
     new_workbook = TSC.WorkbookItem('test', 'ee8c6e70-43b6-11e6-af4f-f7b0d8e20760')
     self.assertRaises(ValueError, self.server.workbooks.publish,
                       new_workbook, os.path.join(TEST_ASSET_DIR, 'SampleDS.tds'),
                       self.server.PublishMode.CreateNew)
示例#18
0
 def test_populate_views_missing_id(self) -> None:
     single_workbook = TSC.WorkbookItem("test")
     self.assertRaises(TSC.MissingRequiredFieldError, self.server.workbooks.populate_views, single_workbook)
示例#19
0
    all_project_items, pagination_item = server.projects.get()
    projectId = [
        proj.id for proj in all_project_items
        if proj.name == deployed.container.name
    ][0]
    print "Found the Project [ %s ] under site [ %s ]" % (
        projectId, deployed.container.site.name)
except ServerResponseError as e:
    raise Exception(e.message)

try:
    # Creating all connections
    all_connections = list()
    for item in deployed.connections:
        temp_connection = ConnectionItem()
        temp_connection.server_address = item.serverAddress
        temp_connection.server_port = item.serverPort
        temp_connection.connection_credentials = ConnectionCredentials(
            item.username, item.password, True)
        all_connections.append(temp_connection)

    wb_item = TSC.WorkbookItem(name=deployed.workbookName,
                               project_id=projectId)
    wb_item._connections = all_connections
    # call the publish method with the workbook item
    wb_item = server.workbooks.publish(wb_item, deployed.file.path,
                                       deployed.publishMode)
    print "Successfully published workbook [%s] " % deployed.workbookName
except ServerResponseError as e:
    raise Exception(e.message)
def main():

    parser = argparse.ArgumentParser(
        description='Publish a workbook to 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',
        '-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',
                        required=True,
                        help='local filepath of the workbook to publish')
    parser.add_argument('--as-job',
                        '-a',
                        help='Publishing asynchronously',
                        action='store_true')
    parser.add_argument('--skip-connection-check',
                        '-c',
                        help='Skip live connection check',
                        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)

    # 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: Get all the projects on server, then look for the default one.
        all_projects, pagination_item = server.projects.get()
        default_project = next(
            (project for project in all_projects if project.is_default()),
            None)

        connection1 = ConnectionItem()
        connection1.server_address = "mssql.test.com"
        connection1.connection_credentials = ConnectionCredentials(
            "test", "password", True)

        connection2 = ConnectionItem()
        connection2.server_address = "postgres.test.com"
        connection2.server_port = "5432"
        connection2.connection_credentials = ConnectionCredentials(
            "test", "password", True)

        all_connections = list()
        all_connections.append(connection1)
        all_connections.append(connection2)

        # Step 3: If default project is found, form a new workbook item and publish.
        overwrite_true = TSC.Server.PublishMode.Overwrite
        if default_project is not None:
            new_workbook = TSC.WorkbookItem(default_project.id)
            if args.as_job:
                new_job = server.workbooks.publish(
                    new_workbook,
                    args.filepath,
                    overwrite_true,
                    connections=all_connections,
                    as_job=args.as_job,
                    skip_connection_check=args.skip_connection_check)
                print("Workbook published. JOB ID: {0}".format(new_job.id))
            else:
                new_workbook = server.workbooks.publish(
                    new_workbook,
                    args.filepath,
                    overwrite_true,
                    connections=all_connections,
                    as_job=args.as_job,
                    skip_connection_check=args.skip_connection_check)
                print("Workbook published. ID: {0}".format(new_workbook.id))
        else:
            error = "The default project could not be found."
            raise LookupError(error)
def main():

    parser = argparse.ArgumentParser(
        description='Publish a workbook to server.')
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--username',
                        '-u',
                        required=True,
                        help='username to sign into server')
    parser.add_argument('--password',
                        '-p',
                        required=True,
                        help='password to sign into server')
    parser.add_argument('--filepath',
                        '-f',
                        required=True,
                        help='filepath to the workbook to publish')
    parser.add_argument('--project',
                        '-pr',
                        required=True,
                        help='target project')
    parser.add_argument(
        '--showtabs',
        '-st',
        choices=['yes', 'no'],
        default='no',
        help='desired show tabs setting (set to yes by default)')
    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')
    parser.add_argument('--as-job',
                        '-a',
                        help='Publishing asynchronously',
                        action='store_true')
    parser.add_argument('--siteid', '-si', help='target site')

    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.TableauAuth(args.username, args.password)

    if args.siteid is not None:
        tableau_auth.siteid = args.siteid

    server = TSC.Server(args.server)

    server.add_http_options({'verify': False})

    overwrite_true = TSC.Server.PublishMode.Overwrite

    with server.auth.sign_in(tableau_auth):

        # Step 2: Get all the projects on server, then look for the default one.
        all_projects, pagination_item = server.projects.get()

        project = next(
            (p
             for p in all_projects if p.name.lower() == args.project.lower()),
            None)

        # Step 3: If default project is found, form a new workbook item and publish.
        if project is not None:
            new_workbook = TSC.WorkbookItem(project.id)

            new_workbook.show_tabs = (args.showtabs == "yes")
            print("Show tabs?: {0}".format(new_workbook.show_tabs))
            if args.as_job:
                new_job = server.workbooks.publish(
                    new_workbook,
                    args.filepath,
                    server.PublishMode.Overwrite,
                    as_job=args.as_job)
                print("Workbook published. JOB ID: {0}".format(new_job.id))
            else:
                new_workbook = server.workbooks.publish(
                    new_workbook,
                    args.filepath,
                    server.PublishMode.Overwrite,
                    as_job=args.as_job)
                print("Workbook published. ID: {0}".format(new_workbook.id))
        else:
            error = "The default project could not be found."
            raise LookupError(error)
示例#22
0
            tableau_auth.site = args.destination_site

            # Signing into another site requires another server object
            # because of the different auth token and site ID.
            with dest_server.auth.sign_in(tableau_auth):

                # Step 5: Find destination site's default project
                pagination_info, dest_projects = dest_server.projects.get()
                target_project = next(
                    (project
                     for project in dest_projects if project.is_default()),
                    None)

                # Step 6: If default project is found, form a new workbook item and publish.
                if target_project is not None:
                    new_workbook = TSC.WorkbookItem(
                        name=args.workbook_name, project_id=target_project.id)
                    new_workbook = dest_server.workbooks.publish(
                        new_workbook,
                        workbook_path,
                        mode=dest_server.PublishMode.Overwrite)
                    print("Successfully moved {0} ({1})".format(
                        new_workbook.name, new_workbook.id))
                else:
                    error = "The default project could not be found."
                    raise LookupError(error)

            # Step 7: Delete workbook from source site and delete temp directory
            source_server.workbooks.delete(all_workbooks[0].id)
        finally:
            shutil.rmtree(tmpdir)
示例#23
0
def main():
    parser = argparse.ArgumentParser(
        description='Connect and publish a workbook to a server.')
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--username',
                        '-u',
                        required=True,
                        help='username to sign into server')
    parser.add_argument('--password',
                        '-p',
                        required=True,
                        help='password for the user')
    parser.add_argument('--dest',
                        '-D',
                        required=True,
                        help='destination server address')
    parser.add_argument('-U',
                        required=True,
                        help='username to sign into destination server')
    parser.add_argument('-P',
                        required=True,
                        help='password for the user on the destination server')
    parser.add_argument('--source', '-S', default=None)
    parser.add_argument('--target', '-T', default=None)
    parser.add_argument('--directory', '-d', default='migrated')
    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')

    parser.add_argument('workbook',
                        help='one or more workbooks to publish',
                        nargs='+')

    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.
    server, server_auth = connect(args.server, args.username, args.password)
    dest, dest_auth = connect(args.dest, args.U, args.P)

    overwrite_true = TSC.Server.PublishMode.Overwrite

    os.makedirs(args.directory, exist_ok=True)

    with server.auth.sign_in(server_auth) and dest.auth.sign_in(dest_auth):

        # Step 2: Get the project on server.
        source = filter_project(args.source, server)
        target = filter_project(args.target, dest)
        print("source: {0} [{1}]".format(server.baseurl, source.name))
        print("destination: {0} [{1}]".format(dest.baseurl, target.name))

        # Step 4: If project is found, build lookup tables.
        if source is not None and target is not None:
            # Step 3: Build a list of datasources.
            ds_source = extract_ds(server, source)
            ds_target = extract_ds(dest, target)
            dbnames_from_to = map_content_url_from_to(ds_source, ds_target)
            # Step 4: Form a new workbook item and publish.
            for wb in args.workbook:
                pub = Workbook(wb)
                for ds in pub.datasources:
                    value = ''
                    if len(ds.connections
                           ) == 1 and ds.connections[0].dbclass == 'sqlproxy':
                        try:
                            if len(ds.caption) == 0 and ds.name in ds_target:
                                value = ds.name
                                ds.connections[0] = ds_target[
                                    value].connections[0]
                            elif ds.connections[0].dbname in dbnames_from_to:
                                value = dbnames_from_to[
                                    ds.connections[0].dbname]
                                ds.connections[0].dbname = value
                            else:
                                value = clean_name(ds.caption)
                                ds.connections[0] = ds_target[
                                    value].connections[0]
                        except LookupError as e:
                            raise LookupError(
                                "lookup information between target and source is inconsistent, datasource caption: {0}, connection: {1}"
                                .format(ds.caption, ds.connections[0].dbname))
                    print("{0}, {1} --> {2}".format(ds.caption, ds.name,
                                                    value))
                wb_migrated = os.path.join(args.directory, wb)
                pub.save_as(wb_migrated)
                new_workbook = TSC.WorkbookItem(target.id)
                try:
                    new_workbook = dest.workbooks.publish(
                        new_workbook, wb_migrated, overwrite_true)
                except TSC.server.endpoint.exceptions.ServerResponseError:
                    dest.version = '2.4'
                    new_workbook = dest.workbooks.publish(
                        new_workbook, wb_migrated, overwrite_true)
                print("workbook published ID: {0}".format(new_workbook.id))
示例#24
0
 def publish(self):
     wb_item = TSC.WorkbookItem(name=self.name, project_id=self.id)
     wb_item = self.session.workbooks.publish(
         wb_item, '..\\repository\\Test Workbook.twb', 'Overwrite')
 def test_publish_invalid_file(self):
     new_workbook = TSC.WorkbookItem('test', 'ee8c6e70-43b6-11e6-af4f-f7b0d8e20760')
     self.assertRaises(IOError, self.server.workbooks.publish, new_workbook, '.',
                       self.server.PublishMode.CreateNew)
示例#26
0
 def test_publish_invalid_file(self) -> None:
     new_workbook = TSC.WorkbookItem("test", "ee8c6e70-43b6-11e6-af4f-f7b0d8e20760")
     self.assertRaises(IOError, self.server.workbooks.publish, new_workbook, ".", self.server.PublishMode.CreateNew)
    # Need to modify any data connections along the way? Do them here
    # First uncomment the document API import at the top of the script,
    # then make your data connection modifications at will

    #sourceWB = Workbook(downloaded_file)
    #sourceWB.datasources[0].connections[0].dbname = "newDB"
    #sourceWB.save_as(sourceWorkbook + '.twbx')
    #print("\nData connection updated and saved to {0}.twbx".format(sourceWorkbook))

print("\nLogged out of source server")
tableau_auth = TSC.TableauAuth(destinationUsername,
                               destinationPassword,
                               site_id=destinationSiteID)
server = TSC.Server(destinationServer)
server.version = destinationAPIVersion

print("\nSigning into destination server")
with server.auth.sign_in(tableau_auth):
    print("\nLogged in to destination server")
    req_option = TSC.RequestOptions()
    req_option.filter.add(
        TSC.Filter(TSC.RequestOptions.Field.Name,
                   TSC.RequestOptions.Operator.Equals, destinationProject))
    all_projects, pagination_item = server.projects.get(req_option)
    wb_item = TSC.WorkbookItem(name=destinationWorkbook,
                               project_id=all_projects[0].id)
    print("\nPublishing workbook")
    wb_item = server.workbooks.publish(wb_item, sourceWorkbook + '.twbx',
                                       'Overwrite')
    print("\nWorkbook published, all done!")
def main():

    parser = argparse.ArgumentParser(
        description='Publish a workbook to server.')
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--username',
                        '-u',
                        required=True,
                        help='username to sign into server')
    parser.add_argument('--filepath',
                        '-f',
                        required=True,
                        help='filepath to the workbook to publish')
    parser.add_argument('--logging-level',
                        '-l',
                        choices=['debug', 'info', 'error'],
                        default='error',
                        help='desired logging level (set to error by default)')
    parser.add_argument('--as-job',
                        '-a',
                        help='Publishing asynchronously',
                        action='store_true')

    args = parser.parse_args()

    password = getpass.getpass("Password: "******"mssql.test.com"
        connection1.connection_credentials = ConnectionCredentials(
            "test", "password", True)

        connection2 = ConnectionItem()
        connection2.server_address = "postgres.test.com"
        connection2.server_port = "5432"
        connection2.connection_credentials = ConnectionCredentials(
            "test", "password", True)

        all_connections = list()
        all_connections.append(connection1)
        all_connections.append(connection2)

        # Step 3: If default project is found, form a new workbook item and publish.
        if default_project is not None:
            new_workbook = TSC.WorkbookItem(default_project.id)
            if args.as_job:
                new_job = server.workbooks.publish(new_workbook,
                                                   args.filepath,
                                                   overwrite_true,
                                                   connections=all_connections,
                                                   as_job=args.as_job)
                print("Workbook published. JOB ID: {0}".format(new_job.id))
            else:
                new_workbook = server.workbooks.publish(
                    new_workbook,
                    args.filepath,
                    overwrite_true,
                    connections=all_connections,
                    as_job=args.as_job)
                print("Workbook published. ID: {0}".format(new_workbook.id))
        else:
            error = "The default project could not be found."
            raise LookupError(error)
def main():

    parser = argparse.ArgumentParser(
        description="Move one workbook from the"
        "default project of the default site to"
        "the default project of another site."
    )
    # 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-site", "-d", required=True, help="name of site 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 both sites on server
    tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site)

    source_server = TSC.Server(args.server)
    dest_server = TSC.Server(args.server)

    with source_server.auth.sign_in(tableau_auth):
        # Step 2: Query workbook to move
        req_option = TSC.RequestOptions()
        req_option.filter.add(
            TSC.Filter(TSC.RequestOptions.Field.Name, TSC.RequestOptions.Operator.Equals, args.workbook_name)
        )
        all_workbooks, pagination_item = source_server.workbooks.get(req_option)

        # Step 3: Download workbook to a temp directory
        if len(all_workbooks) == 0:
            print("No workbook named {} found.".format(args.workbook_name))
        else:
            tmpdir = tempfile.mkdtemp()
            try:
                workbook_path = source_server.workbooks.download(all_workbooks[0].id, tmpdir)

                # Step 4: Check if destination site exists, then sign in to the site
                all_sites, pagination_info = source_server.sites.get()
                found_destination_site = any(
                    (True for site in all_sites if args.destination_site.lower() == site.content_url.lower())
                )
                if not found_destination_site:
                    error = "No site named {} found.".format(args.destination_site)
                    raise LookupError(error)

                tableau_auth.site_id = args.destination_site

                # Signing into another site requires another server object
                # because of the different auth token and site ID.
                with dest_server.auth.sign_in(tableau_auth):

                    # Step 5: Create a new workbook item and publish workbook. Note that
                    # an empty project_id will publish to the 'Default' project.
                    new_workbook = TSC.WorkbookItem(name=args.workbook_name, project_id="")
                    new_workbook = dest_server.workbooks.publish(
                        new_workbook, workbook_path, mode=TSC.Server.PublishMode.Overwrite
                    )
                    print("Successfully moved {0} ({1})".format(new_workbook.name, new_workbook.id))

                # Step 6: Delete workbook from source site and delete temp directory
                source_server.workbooks.delete(all_workbooks[0].id)

            finally:
                shutil.rmtree(tmpdir)
def main():

    parser = argparse.ArgumentParser(description='Explore workbook functions supported by the Server API.')
    parser.add_argument('--server', '-s', required=True, help='server address')
    parser.add_argument('--username', '-u', required=True, help='username to sign into server')
    parser.add_argument('--publish', '-p', metavar='FILEPATH', help='path to workbook to publish')
    parser.add_argument('--download', '-d', metavar='FILEPATH', help='path to save downloaded workbook')
    parser.add_argument('--preview-image', '-i', metavar='FILENAME',
                        help='filename (a .png file) to save the preview image')
    parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
                        help='desired logging level (set to error by default)')

    args = parser.parse_args()

    password = getpass.getpass("Password: "******"Workbook published. ID: {}".format(new_workbook.id))
            else:
                print('Publish failed. Could not find the default project.')

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

        if all_workbooks:
            # Pick one workbook from the list
            sample_workbook = all_workbooks[0]

            # Populate views
            server.workbooks.populate_views(sample_workbook)
            print("\nName of views in {}: ".format(sample_workbook.name))
            print([view.name for view in sample_workbook.views])

            # Populate connections
            server.workbooks.populate_connections(sample_workbook)
            print("\nConnections for {}: ".format(sample_workbook.name))
            print(["{0}({1})".format(connection.id, connection.datasource_name)
                   for connection in sample_workbook.connections])

            # Update tags and show_tabs flag
            original_tag_set = set(sample_workbook.tags)
            sample_workbook.tags.update('a', 'b', 'c', 'd')
            sample_workbook.show_tabs = True
            server.workbooks.update(sample_workbook)
            print("\nWorkbook's old tag set: {}".format(original_tag_set))
            print("Workbook's new tag set: {}".format(sample_workbook.tags))
            print("Workbook tabbed: {}".format(sample_workbook.show_tabs))

            # Delete all tags that were added by setting tags to original
            sample_workbook.tags = original_tag_set
            server.workbooks.update(sample_workbook)

            # Add tag to just one view
            sample_view = sample_workbook.views[0]
            original_tag_set = set(sample_view.tags)
            sample_view.tags.add("view_tag")
            server.views.update(sample_view)
            print("\nView's old tag set: {}".format(original_tag_set))
            print("View's new tag set: {}".format(sample_view.tags))

            # Delete tag from just one view
            sample_view.tags = original_tag_set
            server.views.update(sample_view)

            if args.download:
                # Download
                path = server.workbooks.download(sample_workbook.id, args.download)
                print("\nDownloaded workbook to {}".format(path))

            if args.preview_image:
                # Populate workbook preview image
                server.workbooks.populate_preview_image(sample_workbook)
                with open(args.preview_image, 'wb') as f:
                    f.write(sample_workbook.preview_image)
                print("\nDownloaded preview image of workbook to {}".format(os.path.abspath(args.preview_image)))