def test_can_open_twbx_and_save_as_changes(self):
        new_twbx_filename = 'newtwbx.twbx'
        original_wb = Workbook(self.workbook_file.name)
        original_wb.datasources[0].connections[0].server = 'newdb'
        original_wb.save_as(new_twbx_filename)

        new_wb = Workbook(new_twbx_filename)
        self.assertEqual(new_wb.datasources[0].connections[0].server, 'newdb')

        os.unlink(new_twbx_filename)
    def test_can_open_twbx_and_save_as_changes(self):
        new_twbx_filename = 'newtwbx.twbx'
        original_wb = Workbook(self.workbook_file.name)
        original_wb.datasources[0].connections[0].server = 'newdb'
        original_wb.save_as(new_twbx_filename)

        new_wb = Workbook(new_twbx_filename)
        self.assertEqual(new_wb.datasources[0].connections[
                         0].server, 'newdb')

        os.unlink(new_twbx_filename)
示例#3
0
from tableaudocumentapi import Workbook
from tableaudocumentapi import Connection

sourceWB = Workbook('TestCase3.twbx')

#Allowing the user to choose whether to replace the datasource with an embedded or published connection
user_login = ""
print "The workbook is currently connected to a flat file and a published datasource but can be replaced by an alternative embedded or published connection respectively. The embedded connection will fail due to differences in table names but the published connection will not. The published connection can be found in the Presales site. Choose the type of datasource you would like to replace the existing connection with : "
user_login = raw_input("Please enter your demoapac.tableau.com username: "******"sqlproxy":
            j.server = "sql.databender.net, 14333"
            j.dbname = "Superstore"
            j.dbclass = "sqlserver"
            j.username = "******"

        elif j.dbclass == "sqlproxy":
            j.server = "https://demoapac.tableau.com"
            j.dbname = "TestCase3-destination"
            j.username = "******"

#Saving the workbook
Workbook.save_as(sourceWB, 'TestCase3 output.twbx')

print ""
print "The workbook connections have been updated. Please open the newly created workbook to test."
示例#4
0
db.close()

###Creating duplicate copies of workbooks###
sourceWB = Workbook('Base.twbx')
sourceDS = Datasource.from_file('Base.tdsx')

for i in range(0, len(uniqueField)):
    for x in sourceWB.datasources:
        for j in x.connections:
            j.dbname = schema[i]
            j.username = db_username[i]
    for j in sourceDS.connections:
        j.dbname = schema[i]
        j.username = db_username[i]
    #Saving the workbook and datasource
    Workbook.save_as(sourceWB, uniqueField[i] + '.twbx')
    Datasource.save_as(sourceDS, uniqueField[i] + '.tdsx')

###Creating sites, projects and users if they don't exist, and publishing the workbooks###
server = TSC.Server('server')
tableau_auth = TSC.TableauAuth('username', 'password')

with server.auth.sign_in(tableau_auth):
    all_sites, pagination_item = server.sites.get()

site_check = 0
for i in range(0, len(uniqueField)):
    ###Ignoring process if site already exists###
    for site in all_sites:
        if site.name == uniqueField[i]:
            site_check = 1
import csv              # so we can work with our database list (in a CSV file)

############################################################
# Step 1)  Use Workbook object from the Document API
############################################################
from tableaudocumentapi import Workbook

############################################################
# Step 2)  Open the .twb we want to replicate
############################################################
sourceWB = Workbook('sample-superstore.twb')

############################################################
# Step 3)  Use a database list (in CSV), loop thru and
#          create new .twb's with their settings
############################################################
with open('databases.csv') as csvfile:
    databases = csv.DictReader(csvfile, delimiter=',', quotechar='"')
    for row in databases:
        # Set our unique values for this database
        sourceWB.datasources[0].connections[0].server = row['Server']
        sourceWB.datasources[0].connections[0].dbname = row['Database']
        sourceWB.datasources[0].connections[0].username = row['User']
        # Save our newly created .twb with the new file name
        sourceWB.save_as(row['DBFriendlyName'] + ' - Superstore' + '.twb')
示例#6
0
import csv  # so we can work with our database list (in a CSV file)

############################################################
# Step 1)  Use Workbook object from the Document API
############################################################
from tableaudocumentapi import Workbook

############################################################
# Step 2)  Open the .twb we want to replicate
############################################################
sourceWB = Workbook('sample-superstore.twb')

############################################################
# Step 3)  Use a database list (in CSV), loop thru and
#          create new .twb's with their settings
############################################################
with open('databases.csv') as csvfile:
    databases = csv.DictReader(csvfile, delimiter=',', quotechar='"')
    for row in databases:
        # Set our unique values for this database
        sourceWB.datasources[0].connections[0].server = row['Server']
        sourceWB.datasources[0].connections[0].dbname = row['Database']
        sourceWB.datasources[0].connections[0].username = row['User']
        # Save our newly created .twb with the new file name
        sourceWB.save_as(row['DBFriendlyName'] + ' - Superstore' + '.twb')
示例#7
0
from pathlib import Path
import requests
from tableaudocumentapi import Workbook
import os
import sys

filename = Path('metadata.pdf')
url = 'https://www.echr.coe.int/Documents/Application_Form_ENG.pdf'
response = requests.get(url)
filename.write_bytes(response.content)

sourceWB = Workbook(file_name)

sourceWB.save_as(os.path.join(os.path.dirname(filename)))


def file_save_as(self):
    fout = asksaveasfilename(defaultextension='.pdf')
    try:
        with open(fout, 'w') as output:
            for x in self.entries:
                output.write(x.get())
    except FileNotFoundError:
        print("Cancelled save or error in filename")


file_save_as()
# import sys
# import os
# import pathlib
示例#8
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))
示例#9
0
文件: tableau.py 项目: hkjinlee/pyda
# -*- coding: utf-8 -*-
'''
Tableau 예제

!pip install tableaudocumentapi
'''

from tableaudocumentapi import Workbook

wb = Workbook('data/empty.twb')

Workbook.save_as(wb, 'data/iris.twb')