def show_materialized_views_status(args, password, site_content_url): tableau_auth = TSC.TableauAuth(args.username, password, site_id=site_content_url) server = TSC.Server(args.server, use_server_version=True) enabled_sites = set() with server.auth.sign_in(tableau_auth): # For server admin, this will prints all the materialized views enabled sites # For other users, this only prints the status of the site they belong to print("Materialized views is enabled on sites:") # only server admins can get all the sites in the server # other users can only get the site they are in for site in TSC.Pager(server.sites): if site.materialized_views_mode != "disable": enabled_sites.add(site) print("Site name: {}".format(site.name)) print('\n') print("Materialized views is enabled on workbooks:") # Individual workbooks can be enabled only when the sites they belong to are enabled too for site in enabled_sites: site_auth = TSC.TableauAuth(args.username, password, site.content_url) with server.auth.sign_in(site_auth): for workbook in TSC.Pager(server.workbooks): if workbook.materialized_views_config[ 'materialized_views_enabled']: print("Workbook: {} from site: {}".format( workbook.name, site.name))
def getSites(serverName): sites = [] try: # Step 1: Sign in to server. if args.si: tableau_auth = TSC.TableauAuth(args.u, password, site_id=args.si) else: tableau_auth = TSC.TableauAuth(args.u, password, site_id="") server = TSC.Server(serverName) server.add_http_options({'verify': False}) # The new endpoint was introduced in Version 2.4 server.version = APIVERSION with server.auth.sign_in(tableau_auth): # query the sites if args.si: sites.append(server.sites.get_by_name(args.si)) else: sites.extend(list(TSC.Pager(server.sites))) return sites except Exception as e: log.logger.error(f"{sys.exc_info()[0]}, {e}") os._exit(1) return False
def create_site(server="out"): new_site = TSC.SiteItem(name=tableau_servers[server]["site_name"], content_url=tableau_servers[server]["site_id"]) tableau_servers["out"]["auth"] = TSC.TableauAuth( tableau_servers["out"]["user"], tableau_servers["out"]["password"]) with tableau_servers[server]["server"].auth.sign_in( tableau_servers[server]["auth"]): try: tableau_servers[server]["server"].sites.create(new_site) except Exception as e: print("WARNING: {}".format(e)) tableau_servers[server]["auth"] = TSC.TableauAuth( tableau_servers[server]["user"], tableau_servers[server]["password"], site_id=tableau_servers[server]["site_id"])
def test_sign_in_without_auth(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.TableauAuth('', '') self.assertRaises(TSC.ServerResponseError, self.server.auth.sign_in, tableau_auth)
def main(): parser = argparse.ArgumentParser(description='Interact with Webhooks on Tableau Server.') parser.add_argument('action', choices=['create', 'get', 'list', 'delete', 'test'], help='Action to take with Webhooks') parser.add_argument('--server', '-S', help='Server address') parser.add_argument('--site', '-s', help='Site name') parser.add_argument('--username', '-u', help='Username to sign into server') args = parser.parse_args() server = args.server if args.server else input('Server URL: ') site = args.site if args.site else input('Site name: ') username = args.username if args.username else input('Username: '******'Password: '******'Signed into ' + tableau_auth.site_id + '.') action = args.action if action == 'create': create_webhook(server) elif action == 'get': get_webhook(server) elif action == 'list': list_webhooks(server) elif action == 'delete': delete_webhook(server) elif action == 'test': test_webhook(server)
def close(self): """ Perform any necessary cleanup """ self.e.close() tableau_auth = TSC.TableauAuth(self.username, self.password, site_id=self.site_id) server = TSC.Server(self.server_url, use_server_version=True) server.auth.sign_in(tableau_auth) try: if self.datasource: server.datasources.publish(self.datasource, self.output_file, 'Overwrite', connection_credentials=None) else: new_datasource = TSC.DatasourceItem(self.project.id, name=self.output_table) new_datasource = server.datasources.publish( new_datasource, self.output_file, 'CreateNew') except: raise finally: server.auth.sign_out() os.remove(self.output_file)
def publishToTableauServer(username, password, project, tabUrl, unique_filename, mode): tableau_auth = TSC.TableauAuth(username, password) server = TSC.Server(tabUrl) server.add_http_options({'verify': CA}) project_id = '' file_path = unique_filename with server.auth.sign_in(tableau_auth): all_project_items, pagination_item = server.projects.get() for proj in all_project_items: if proj.name == project: project_id = proj.id new_datasource = TSC.DatasourceItem(project_id) try: new_datasource = server.datasources.publish( new_datasource, file_path, mode) logger.debug(' DataSource Published') except ServerResponseError as e: server.auth.sign_out() logger.error(' DataSource failed to publish ') logger.error(e) raise Exception(e) sys.exit(1) server.auth.sign_out() if os.path.exists(unique_filename): os.remove(unique_filename) else: logger.warning("The file does not exist")
def __init__(self): # create an auth object self.tableau_auth = TSC.TableauAuth('ldua', 'workharder247', site_id='vpr') # create an instance for your self.server self.server = TSC.Server('https://tableau.sfu.ca')
def publishDataSource(filePath, projectId): tableauAuth = TSC.TableauAuth(tableauUserId, tableauPassword) server = TSC.Server(tableauServerAddress) if tableauIgnoreSslCert: server.add_http_options({'verify': False}) server.auth.sign_in(tableauAuth) datasourceCredentials = TSC.ConnectionCredentials(name=pgUser, password=pgPassword) datasource = TSC.DatasourceItem(projectId) if useCustomSQL: datasource.name = dataSourceName datasource = server.datasources.publish(datasource, filePath, 'CreateNew', datasourceCredentials) if verbose: print('Published datasource {} to Tableau Server running at {}'.format( datasource.name, tableauServerAddress)) lineClear() server.auth.sign_out()
def main(): request_options = TSC.RequestOptions(pagesize=1000) content = fwapi() # tableau_auth = TSC.TableauAuth('20040201', 'GT2020!qaz', site_id='') tableau_auth = TSC.TableauAuth('GT_Account', 'GT2020123456', site_id='') server = TSC.Server('https://fas-gt.com:8000', use_server_version=True) # server = TSC.Server('https://tab.sucgm.com:10000') infos = content['data'] print(infos) connect = sqlcon() cursor = connect.cursor() # 创建一个游标对象,python里的sql语句都要通过cursor来执行 allgroup = [] for info in infos: # 遍历获取群组id和群组名称 groupid = info['id'] groupname = info['rolesmark'] # 获取群组名称 groupname = groupname[:-5] # 将群组名称后的 -致同群组 字段删除 allgroup.append([groupid, groupname]) # sql = "select GroupName from OFW_GROUP_TAB_ALLOWED where IsDelete = 0 and GroupId = %s" sql = "select GroupName from OFW_GROUP_TAB_ALLOWED_TEST where IsDelete = 0 and GroupId = %s" cursor.execute(sql, groupid) row = cursor.fetchall() # 读取查询结果, # print(row) rowCount = len(row) if rowCount == 0: # sql = "insert into OFW_GROUP_TAB_ALLOWED (GroupId,GroupName) VALUES (%s,%s)" sql = "insert into OFW_GROUP_TAB_ALLOWED_TEST (GroupId,GroupName) VALUES (%s,%s)" value = (groupid, groupname) cursor.execute(sql, value) # 提交到数据库执行 connect.commit() with server.auth.sign_in(tableau_auth): newgroup = TSC.GroupItem(groupname) newgroup = server.groups.create(newgroup) # print(newgroup.name) print('群组' + groupname + '添加成功') else: rawdata = row[0][0] if rawdata != groupname: print('群组' + rawdata + '名称需要修改') with server.auth.sign_in(tableau_auth): # 通过TSM 修改user对应群组 all_groups, pagination_item = server.groups.get( request_options) for group in all_groups: if group.name == rawdata: group.name = groupname newg = server.groups.update(group) break # sql = "Update OFW_GROUP_TAB_ALLOWED SET GroupName = %s where GroupId =%s" sql = "Update OFW_GROUP_TAB_ALLOWED_TEST SET GroupName = %s where GroupId =%s" value = (groupname, groupid) cursor.execute(sql, value) # 提交到数据库执行 connect.commit() print("完成对 " + groupname + " 群组名称的更改") else: print('已存在' + groupname + ',无需更改')
def update_workbook(args, materialized_views_config, password, site_content_url): if args.path_list is None and args.name_list is None: print( "Use '--path-list <filename>' or '--name-list <filename>' to specify the path of a list of workbooks" ) print('\n') return False tableau_auth = TSC.TableauAuth(args.username, password, site_id=site_content_url) server = TSC.Server(args.server, use_server_version=True) with server.auth.sign_in(tableau_auth): if not assert_site_enabled_for_materialized_views( server, site_content_url): return False if args.path_list is not None: workbook_path_mapping = parse_workbook_path(args.path_list) all_projects = { project.id: project for project in TSC.Pager(server.projects) } update_workbooks_by_paths(all_projects, materialized_views_config, server, workbook_path_mapping) elif args.name_list is not None: update_workbooks_by_names(args.name_list, server, materialized_views_config) return True
def update_project_by_name(args, materialized_views_config, password, site_content_url): if args.project_name is None: print( "Use --project-name <project name> to specify the name of the project" ) return False tableau_auth = TSC.TableauAuth(args.username, password, site_content_url) server = TSC.Server(args.server, use_server_version=True) with server.auth.sign_in(tableau_auth): if not assert_site_enabled_for_materialized_views( server, site_content_url): return False # get all projects with given name projects = [ project for project in TSC.Pager(server.projects) if project.name == args.project_name ] if not assert_project_valid(args.project_name, projects): return False if len(projects) > 1: possible_paths = get_project_paths(server, projects) print("Project name is not unique, use '--project_path <path>'") print("Possible project paths:") print_paths(possible_paths) print('\n') return False else: update_project(projects[0], server, materialized_views_config) return True
def update_project_by_path(args, materialized_views_config, password, site_content_url): if args.project_path is None: print( "Use --project_path <project path> to specify the path of the project" ) return False tableau_auth = TSC.TableauAuth(args.username, password, site_content_url) server = TSC.Server(args.server, use_server_version=True) project_name = args.project_path.split('/')[-1] with server.auth.sign_in(tableau_auth): if not assert_site_enabled_for_materialized_views( server, site_content_url): return False projects = [ project for project in TSC.Pager(server.projects) if project.name == project_name ] if not assert_project_valid(args.project_path, projects): return False possible_paths = get_project_paths(server, projects) update_project(possible_paths[args.project_path], server, materialized_views_config) return True
def main(): parser = argparse.ArgumentParser( description='Creates sample schedules for each type of frequency.') 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('--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: ") # 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.TableauAuth(args.username, password) server = TSC.Server(args.server) with server.auth.sign_in(tableau_auth): group = TSC.GroupItem('test') group = server.groups.create(group) print(group)
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=None, help='site to log into, do not specify for default site') parser.add_argument('--username', '-u', required=True, help='username to sign into server') parser.add_argument('--password', '-p', default=None, help='password for the user') 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', 'view']) args = parser.parse_args() if args.password is None: password = getpass.getpass("Password: ") else: password = args.password # 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.TableauAuth(args.username, password, 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 }.get(args.resource_type) for resource in TSC.Pager(endpoint.get): print(resource.id, resource.name, resource.content_url)
def main(): print("Select CSV File") CSV_filename = tk.filedialog.askopenfilename( initialdir=os.getcwd(), title="Select CSV file", filetypes=(("csv files", "*.csv"), ("all files", "*.*"))) print("Select End File Location") Save_location = tk.filedialog.askdirectory(initialdir=os.getcwd(), title="Choose Directory") userName, password, serverInstance, siteName, workbook_Name, dashboard_Name, user_Email = entCred.enterCredentailsAutomatic( ) print(userName, siteName, workbook_Name, dashboard_Name) TableauAuthentication = TSC.TableauAuth(userName, password, site_id=siteName) TSC_server = TSC.Server(serverInstance, use_server_version=True) start_time = time.time() dashboardViewer.CSV_ImageRequest(TSC_server, TableauAuthentication, CSV_filename, Save_location, workbook_Name, dashboard_Name, user_Email) print("--- %s seconds ---" % (time.time() - start_time))
def publishExtract(extract_file=None, server_address=None, site=None, project=None, username=None, password=None): tableau_auth = TSC.TableauAuth(username, password) server = TSC.Server(server_address) server.use_highest_version() with server.auth.sign_in(tableau_auth): # Query projects for use when demonstrating publishing and updating all_projects, pagination_item = server.projects.get() default_project = next( (project for project in all_projects if project.is_default()), None) if default_project is not None: new_datasource = TSC.DatasourceItem(default_project.id) new_datasource = server.datasources.publish( new_datasource, args.publish, TSC.Server.PublishMode.Overwrite) print("Datasource published. ID: {}".format(new_datasource.id)) else: print("Publish failed. Could not find the default project.")
class TableauServerConnection: FILE_PATH = os.path.dirname(Tests.__file__) username = os.getenv('USERNAME') password = os.getenv('PASSWORD') server_url = os.getenv('SERVER_URL') tableau_auth = TSC.TableauAuth('mll25', 'BobRoss1125!') server = TSC.Server('https://casanalyticsp01.cas.org/') # Current server version : 3.3 server.use_server_version() req_option = TSC.RequestOptions(pagesize=1000) csv_req_option = TSC.CSVRequestOptions() image_req_option = TSC.ImageRequestOptions(imageresolution=TSC.ImageRequestOptions.Resolution.High) image_req_option.vf('Country', 'AUSTRALIA') csv_req_option.vf('Country','AUSTRALIA') with server.auth.sign_in(tableau_auth): all_workbooks, pagination_item = server.workbooks.get() wfound = [workbook for workbook in all_workbooks if workbook.name == 'Enterprise Success Dashboard LIVE'] # pprint(vars(wfound[0])) wconnect = server.workbooks.get_by_id('94d2abea-bced-46d1-831c-edce132b2864') server.workbooks.populate_views(wconnect) vfound = [view for view in wconnect.views if len(view.name) > 0] view_item = vfound[21] server.views.populate_csv(view_item, csv_req_option) with open(f'{FILE_PATH}/CCDAus.csv', 'wb') as f: if os.path.exists(f): os.remove(f) f.write(b''.join(view_item.csv))
def process_data(output_mgr, user_data, logger): tableau_auth = TSC.TableauAuth(user_data.username, user_data.password, user_data.site_name) server = TSC.Server(user_data.server_url) with server.auth.sign_in(tableau_auth): all_datasources, pagination_item = server.datasources.get() datasource = [datasource for datasource in all_datasources if datasource.name == user_data.data_source_name] tdsx_file_path = server.datasources.download(datasource[0].id, filepath=user_data.download_location) logger.display_info_msg("Downloaded the file to {0}.".format(tdsx_file_path)) zip_file_path = re.sub(r'.tdsx', '.zip', tdsx_file_path) if os.path.exists(zip_file_path): os.remove(zip_file_path) os.rename(tdsx_file_path, zip_file_path) zip_download_folder_path = os.path.split(zip_file_path)[0] extract_to_path = zip_download_folder_path + '\\' + user_data.data_source_name +'_extracted' with zipfile.ZipFile(zip_file_path, 'r') as zip_ref: zip_ref.extractall(extract_to_path) data_extracts_folder_path = extract_to_path + '\Data\Extracts' hyper_file_path = data_extracts_folder_path + '\\' + os.listdir(data_extracts_folder_path)[0] updated_hyper_file_path = data_extracts_folder_path + '\\' + user_data.data_source_name + '.hyper' os.rename(hyper_file_path, updated_hyper_file_path) data_out = output_mgr["Output"] data_out.data = pd.DataFrame({"File Location": [updated_hyper_file_path]}) return
def main(): parser = argparse.ArgumentParser(description='Cancel all of the running background jobs.') parser.add_argument('--server', '-s', required=True, help='server address') parser.add_argument('--site', '-S', default=None, help='site to log into, do not specify for default site') parser.add_argument('--username', '-u', required=True, help='username to sign into server') parser.add_argument('--password', '-p', default=None, help='password for the user') 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() if args.password is None: password = getpass.getpass("Password: "******"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 wrapper(srvr, un, pw, *args, **kwargs): """login to tableau server""" server = TSC.Server(srvr) auth = TSC.TableauAuth(un, pw) login = server.auth.sign_in(auth) tableau_item = f(*args, **kwargs) return login
def main(): #Set the query https://help.tableau.com/current/api/metadata_api/en-us/docs/meta_api_examples.html query = """ { databases{ id name } } """ parser = argparse.ArgumentParser(description='Creates sample schedules for each type of frequency.') 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('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error', help='desired logging level (set to error by default)') parser.add_argument('--sitename', '-n', help='fghdhr') args = parser.parse_args() password = getpass.getpass("Password: ") # 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.TableauAuth(args.username, password, args.sitename) server = TSC.Server(args.server) server.version = '3.3' with server.auth.sign_in(tableau_auth): #Query the Metadata API and store the response in resp resp = server.metadata.query(query) datasources = resp['data']
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 test_site_arg_raises_warning(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") tableau_auth = TSC.TableauAuth("user", "password", site="Default") self.assertTrue(any(item.category == DeprecationWarning for item in w))
def download(workbook, view): config = configparser.ConfigParser() config.read(SETTINGS_CONFIGURATION_FILE) server_name = config.get(LOGIN, SERVER) username = config.get(LOGIN, USERNAME) password = config.get(LOGIN, PASSWORD) site = config.get(LOGIN, SITE) server = tsc.Server(server_name) tableau_auth = tsc.TableauAuth(username, password, site) server.auth.sign_in(tableau_auth) token = server.auth_token url = server_name + "/t/" + site + "/views/" + workbook + "/" + view + ".pdf" headers = { 'Cookie': 'workgroup_session_id=' + token, 'Connection': 'keep-alive' } r = requests.get(url, headers=headers) if (r.content[1:4]) != b'PDF': raise RuntimeError( "Wrong arguments, file not found. Check your workbook and sheet in settings.ini" ) with open(temp_filepath + view + '.pdf', 'wb') as fd: fd.write(r.content)
def __init__(self): self.tableau_auth = TSC.TableauAuth( 'public', 'public', site_id='Sales') # username/password/sitio self.server = TSC.Server('https://tableau.adminml.com') #Server self.server.version = '2.5' #Changing version self.server.use_server_version() self.working_data = []
def open(self, schema): print('INFO: Given data schema {}'.format(schema)) tableau_auth = TSC.TableauAuth(self.username, self.password, site_id=self.site_id) server = TSC.Server(self.server_url, use_server_version=True) print('Using Tableau server version {}'.format(server.version)) s_info = server.server_info.get() print("\nServer info:") print("\tProduct version: {0}".format(s_info.product_version)) print("\tREST API version: {0}".format(s_info.rest_api_version)) print("\tBuild number: {0}".format(s_info.build_number)) server.auth.sign_in(tableau_auth) all_project_items, pagination_item = server.projects.get() project_match = [proj for proj in all_project_items if proj.name == self.project_name] if len(project_match) > 0: self.project = project_match[0] print('Found project matching {} with id {}'.format(self.project.name, self.project.id)) else: raise ValueError('Project {} does not exist on server'.format(self.project_name)) all_datasources, pagination_item = server.datasources.get() datasource_match = [d for d in all_datasources if d.name == self.output_table ] if len(datasource_match) > 0: self.datasource = datasource_match[0] print('WARN: Found existing table {} with id {}, will be overwritten'.format(self.datasource.name, self.datasource.id)) server.auth.sign_out() # Fairly ugly. We create and delete a temporary file while retaining its name with tempfile.NamedTemporaryFile(prefix="output", suffix=".hyper", dir=os.getcwd()) as f: self.output_file = f.name print("Tmp file: {}".format(self.output_file)) self.e = TableauExport(self.output_file , schema['columns'])
def connectToServer(self): try: self.tableau_auth = TSC.TableauAuth(self.username, self.password, self.site) self.serverConnection = TSC.Server(self.serverUrl, use_server_version=True) self.serverConnection.auth.sign_in(self.tableau_auth) print( "\n----------------------------------------------------------\n" ) print("Connected to the Tableau Server!") s_info = self.serverConnection.server_info.get() print("\nServer info:") print("\tProduct version: {0}".format(s_info.product_version)) print("\tREST API version: {0}".format(s_info.rest_api_version)) print("\tBuild number: {0}".format(s_info.build_number)) print("\tAddress: {}".format(self.serverConnection.server_address)) print("\tUsername: {}".format(self.username)) print("\tSite name: {}".format(self.site)) print( "\n----------------------------------------------------------\n" ) self.connected = 1 return self except: print("\nInvalid login information!!!" ) # Create limited number of tries print("Error: {}".format(sys.exc_info())) return ""
def load_workbooks(): """ :return: """ # authorize user tableau_auth = TSC.TableauAuth(config.username, config.password) # connect to server server = TSC.Server(config.server_name) with server.auth.sign_in(tableau_auth): for wb in TSC.Pager(server.workbooks): try: path = server.workbooks.download(wb.id, filepath=config.twb_path) # из коробки не сохраняет кирилицу - даём нормальное имя и на всякий случай удаляем расширение, # т.к. не всегда оно сохраняется и заменяем слеши wb_name = re.sub(r'\.twbx?', '', str(wb.name.encode('utf-8'))).replace('/', '\\') os.rename(path, '{}{}'.format(config.twb_path, wb_name)) # если отчёт скачался вместе с экстрактом - выпиливаем экстракт if zipfile.is_zipfile('{}{}'.format(config.twb_path, wb_name)): os.rename('{}{}'.format(config.twb_path, wb_name), '{}{}.twbx'.format(config.twb_path, wb_name)) else: os.rename('{}{}'.format(config.twb_path, wb_name), '{}{}.twb'.format(config.twb_path, wb_name)) except TSC.server.endpoint.exceptions.ServerResponseError: pass
def main(): request_options = TSC.RequestOptions(pagesize=1000) tableau_auth = TSC.TableauAuth('20040201', 'GT2020!qaz', site_id='') # tableau_auth = TSC.TableauAuth('GT_Account', 'GT2020123456', site_id='') # server = TSC.Server('https://fas-gt.com:8000') server = TSC.Server('https://tab.sucgm.com:10000', use_server_version=True) f = open('user&pwd.csv', 'w', encoding='utf-8', newline='' "") # 2. 基于文件对象构建 csv写入对象 csv_writer = csv.writer(f) # 3. 构建列表头 csv_writer.writerow(["Workcode", "Password"]) column = readExcel() with server.auth.sign_in(tableau_auth): for workcode in column: # 将新用户添加至user表 all_users, pagination_item = server.users.get(request_options) for user in all_users: if user.name == workcode: pwd = pwdcreate() print(pwd) user1 = server.users.update(user, password=pwd) csv_writer.writerow([workcode, pwd]) # else: # print(index) f.close()