背景:
目前Tableau报表是通过定时任务刷新的,但是现在希望ETL任务执行完后,就自动启Tableau刷新任务,而不是等待到定时时刻,从而节省等待时间。
方案:
tableau数据提取可以通过tabcmd命令在终端中进行,那么相应地,我们就可以通过python中的os.system/os.popen方法执行cmd命令刷新数据。即,
tabcmd命令帮助文档参见这里
流程:
我们这里只用到3个命令,该3个命令对应流程中的3个步骤。
需要强调说明的是refreshextracts命令只是启动数据提取,启动成功即完成,而非数据刷新完成算完成。
**
本地计算机上要先配置好tabcmd的开发环境。
在安装Tableau Server的时候默认是将tabcmd环境一起安装的,但有时候我们需要在其他机器上远程连接Tableau Server,该机器上并未有tabcmd环境,则需要我们自行单独配置。
比如我们现在Tableau服务器是在xxx.xxx.xxx.140上,而我现在是在xxx.xxx.xxx.160服务器上去连接,而160服务器上并没有tabcmd环境,那么我就需要先在160上配置好tabcmd环境,才能使用tabcmd命令。
安装及使用过程参加如下文档:
接下来进入正式内容:
为了安全性,凡是有关用户名密码等信息,全部不直接写在程序里,都是从外部读入。
# encoding=utf-8
import os, sys
import time
CurrentFile = os.path.abspath(__file__)
CurrentPath = os.path.dirname(CurrentFile)
FatherPath = os.path.dirname(CurrentPath)
sys.path.insert(0, FatherPath)
import configparser
cf = configparser.ConfigParser()
cf.read(os.path.join(FatherPath, 'doc/config.ini'))
tabcmd_dict = dict(cf.items('tabcmd-config'))
# 配置文件
tabcmd_path = tabcmd_dict['tabcmd_path']
server_private = tabcmd_dict['server_private'] # 内网ip,程序在tableau server服务器上时使用
server_public = tabcmd_dict['server_public'] # 公网ip,外部访问
user = tabcmd_dict['user']
pwd = tabcmd_dict['pwd']
def tabcmd_logoin(server_public, user, pwd):
# os.chdir(tabcmd_path) # 如果没有把tabcmd添加到环境变量里,则需要先切换到该路径
tabcmd_login = F"tabcmd login -s {server_public} -u {user} -p {pwd}"
# os.system('chcp 65001') # 如果出现乱码需要将其设置为utf-8
status = os.system(tabcmd_login)
return status
def tabcm_refresh(project, workbook):
tabcmd_refresh = F'tabcmd refreshextracts --project "{project}" --workbook "{workbook}"'
status = os.system(tabcmd_refresh) # 返回0表示成功,其他表示失败
if status == 0:
status = 'success'
else:
print(tabcmd_refresh)
status ='failed'
now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
return {
'project': project, 'workbook': workbook, 'statuas': status, 'update_start_time': now}
def tabcmd_logout():
os.system('tabcmd logout')
def main(projects, workbooks):
login_status = tabcmd_logoin(server_public, user, pwd)
if login_status == 0:
for project, workbook in zip(projects, workbooks):
data = tabcm_refresh(project, workbook)
print(data)
tabcmd_logout()
else:
print('login failed!')
if __name__ == '__main__':
projects = ['Default', ]
workbooks = ['test', ]
main(projects, workbooks)