forked from VathsalaAchar/tableau_rest_api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtableau_rest_api.py
3863 lines (3452 loc) · 171 KB
/
tableau_rest_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Python 2.x only
import urllib2
# For parsing XML responses
from lxml import etree
# StringIO helps with lxml UTF8 parsing
from StringIO import StringIO
import math
import time
import random
import os
import re
import copy
import zipfile
import shutil
import sys
from HTMLParser import HTMLParser
# Implements logging features across all objects
class TableauBase(object):
def __init__(self):
# In reverse order to work down until the acceptable version is found on the server, through login process
self.supported_versions = (u"9.3", u"9.2", u"9.1", u"9.0")
self.logger = None
self.luid_pattern = r"[0-9a-fA-F]*-[0-9a-fA-F]*-[0-9a-fA-F]*-[0-9a-fA-F]*-[0-9a-fA-F]*"
# Defaults, will get updated with each update. Overwritten by set_tableau_server_version
self.version = u"9.3"
self.api_version = u"2.2"
self.tableau_namespace = u'http://tableau.com/api'
self.ns_map = {'t': 'http://tableau.com/api'}
self.ns_prefix = '{' + self.ns_map['t'] + '}'
self.site_roles = (
u'Interactor',
u'Publisher',
u'SiteAdministrator',
u'Unlicensed',
u'UnlicensedWithPublish',
u'Viewer',
u'ViewerWithPublish',
u'ServerAdministrator'
)
self.server_content_roles = {
u"2.0": {
u"project": (
u'Viewer',
u'Interactor',
u'Editor',
u'Data Source Connector',
u'Data Source Editor',
u'Publisher',
u'Project Leader'
),
u"workbook": (
u'Viewer',
u'Interactor',
u'Editor'
),
u"datasource": (
u'Data Source Connector',
u'Data Source Editor'
)
},
u"2.1": {
u"project": (
u'Viewer',
u'Publisher',
u'Project Leader'
),
u"workbook": (
u'Viewer',
u'Interactor',
u'Editor'
),
u"datasource": (
u'Editor',
u'Connector'
)
},
u"2.2": {
u"project": (
u'Viewer',
u'Publisher',
u'Project Leader'
),
u"workbook": (
u'Viewer',
u'Interactor',
u'Editor'
),
u"datasource": (
u'Editor',
u'Connector'
)
}
}
self.server_to_rest_capability_map = {
u'Add Comment': u'AddComment',
u'Move': u'ChangeHierarchy',
u'Set Permissions': u'ChangePermissions',
u'Connect': u'Connect',
u'Delete': u'Delete',
u'View Summary Data': u'ExportData',
u'Export Image': u'ExportImage',
u'Download': u'ExportXml',
u'Filter': u'Filter',
u'Project Leader': u'ProjectLeader',
u'View': u'Read',
u'Share Customized': u'ShareView',
u'View Comments': u'ViewComments',
u'View Underlying Data': u'ViewUnderlyingData',
u'Web Edit': u'WebAuthoring',
u'Save': u'Write',
u'all': u'all' # special command to do everything
}
self.available_capabilities = {
u"2.0": {
u"project": (
u'AddComment',
u'ChangeHierarchy',
u'ChangePermissions',
u'Connect',
u'Delete',
u'ExportData',
u'ExportImage',
u'ExportXml',
u'Filter',
u'ProjectLeader',
u'Read',
u'ShareView',
u'ViewComments',
u'ViewUnderlyingData',
u'WebAuthoring',
u'Write'
),
u"workbook": (
u'AddComment',
u'ChangeHierarchy',
u'ChangePermissions',
u'Delete',
u'ExportData',
u'ExportImage',
u'ExportXml',
u'Filter',
u'Read',
u'ShareView',
u'ViewComments',
u'ViewUnderlyingData',
u'WebAuthoring',
u'Write'
),
u"datasource": (
u'ChangePermissions',
u'Connect',
u'Delete',
u'ExportXml',
u'Read',
u'Write'
)
},
u"2.1": {
u"project": (u'ProjectLeader', u"Read", u"Write"),
u"workbook": (
u'AddComment',
u'ChangeHierarchy',
u'ChangePermissions',
u'Delete',
u'ExportData',
u'ExportImage',
u'ExportXml',
u'Filter',
u'Read',
u'ShareView',
u'ViewComments',
u'ViewUnderlyingData',
u'WebAuthoring',
u'Write'
),
u"datasource": (
u'ChangePermissions',
u'Connect',
u'Delete',
u'ExportXml',
u'Read',
u'Write'
)
},
u"2.2": {
u"project": (u'ProjectLeader', u"Read", u"Write"),
u"workbook": (
u'AddComment',
u'ChangeHierarchy',
u'ChangePermissions',
u'Delete',
u'ExportData',
u'ExportImage',
u'ExportXml',
u'Filter',
u'Read',
u'ShareView',
u'ViewComments',
u'ViewUnderlyingData',
u'WebAuthoring',
u'Write'
),
u"datasource": (
u'ChangePermissions',
u'Connect',
u'Delete',
u'ExportXml',
u'Read',
u'Write'
)
}
}
self.permissionable_objects = (u'datasource', u'project', u'workbook')
def set_tableau_server_version(self, tableau_server_version):
"""
:type tableau_server_version: unicode
"""
# API Versioning (starting in 9.2)
if unicode(tableau_server_version)in [u"9.2", u"9.3"]:
if unicode(tableau_server_version) == u"9.2":
self.api_version = u"2.1"
elif unicode(tableau_server_version) == u"9.3":
self.api_version = u"2.2"
self.tableau_namespace = u'http://tableau.com/api'
self.ns_map = {'t': 'http://tableau.com/api'}
self.version = tableau_server_version
self.ns_prefix = '{' + self.ns_map['t'] + '}'
elif unicode(tableau_server_version) in [u"9.0", u"9.1"]:
self.api_version = u"2.0"
self.tableau_namespace = u'http://tableausoftware.com/api'
self.ns_map = {'t': 'http://tableausoftware.com/api'}
self.version = tableau_server_version
self.ns_prefix = '{' + self.ns_map['t'] + '}'
else:
raise InvalidOptionException(u"Please specify tableau_server_version as a string. '9.0' or '9.2' etc...")
# Logging Methods
def enable_logging(self, logger_obj):
if isinstance(logger_obj, Logger):
self.logger = logger_obj
def log(self, l):
if self.logger is not None:
self.logger.log(l)
def start_log_block(self):
if self.logger is not None:
self.logger.start_log_block()
def end_log_block(self):
if self.logger is not None:
self.logger.end_log_block()
def log_uri(self, uri, verb):
if self.logger is not None:
self.logger.log_uri(verb, uri)
def log_xml_request(self, xml, verb):
if self.logger is not None:
self.logger.log_xml_request(verb, xml)
# Method to handle single str or list and return a list
@staticmethod
def to_list(x):
if isinstance(x, (str, unicode)):
l = [x] # Make single into a collection
else:
l = x
return l
# Method to read file in x MB chunks for upload, 10 MB by default (1024 bytes = KB, * 1024 = MB, * 10)
@staticmethod
def read_file_in_chunks(file_object, chunk_size=(1024 * 1024 * 10)):
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data
# You must generate a boundary string that is used both in the headers and the generated request that you post.
# This builds a simple 30 hex digit string
@staticmethod
def generate_boundary_string():
random_digits = [random.SystemRandom().choice('0123456789abcdef') for n in xrange(30)]
s = "".join(random_digits)
return s
# URI is different form actual URL you need to load a particular view in iframe
@staticmethod
def convert_view_content_url_to_embed_url(content_url):
split_url = content_url.split('/')
return 'views/' + split_url[0] + "/" + split_url[2]
# Generic method for XML lists for the "query" actions to name -> id dict
@staticmethod
def convert_xml_list_to_name_id_dict(lxml_obj):
d = {}
for element in lxml_obj:
e_id = element.get("id")
# If list is collection, have to run one deeper
if e_id is None:
for list_element in element:
e_id = list_element.get("id")
name = list_element.get("name")
d[name] = e_id
else:
name = element.get("name")
d[name] = e_id
return d
# Convert a permission
def convert_server_permission_name_to_rest_permission(self, permission_name):
if permission_name in self.server_to_rest_capability_map:
return self.server_to_rest_capability_map[permission_name]
else:
raise InvalidOptionException(u'{} is not a permission name on the Tableau Server'.format(permission_name))
# 32 hex characters with 4 dashes
def is_luid(self, val):
if len(val) == 36:
if re.match(self.luid_pattern, val) is not None:
return True
else:
return False
else:
return False
# Looks at LUIDs in new_obj_list, if they exist in the dest_obj, compares their gcap objects, if match returns True
def are_capabilities_objs_identical_for_matching_luids(self, new_obj_list, dest_obj_list):
self.start_log_block()
# Create a dict with the LUID as the keys for sorting and comparison
new_obj_dict = {}
for obj in new_obj_list:
new_obj_dict[obj.get_luid()] = obj
dest_obj_dict = {}
for obj in dest_obj_list:
dest_obj_dict[obj.get_luid()] = obj
new_obj_luids = new_obj_dict.keys()
dest_obj_luids = dest_obj_dict.keys()
if set(dest_obj_luids).issuperset(new_obj_luids):
# At this point, we know the new_objs do exist on the current obj, so let's see if they are identical
for luid in new_obj_luids:
new_obj = new_obj_dict.get(luid)
dest_obj = dest_obj_dict.get(luid)
self.log(u"Capabilities to be set:")
new_obj_cap_dict = new_obj.get_capabilities_dict()
self.log(unicode(new_obj_cap_dict))
self.log(u"Capabilities that were originally set:")
dest_obj_cap_dict = dest_obj.get_capabilities_dict()
self.log(unicode(dest_obj_cap_dict))
if new_obj_cap_dict == dest_obj_cap_dict:
self.end_log_block()
return True
else:
self.end_log_block()
return False
else:
self.end_log_block()
return False
# Determine if capabilities are already set identically (or identically enough) to skip
def are_capabilities_obj_lists_identical(self, new_obj_list, dest_obj_list):
# Grab the LUIDs of each, determine if they match in the first place
# Create a dict with the LUID as the keys for sorting and comparison
new_obj_dict = {}
for obj in new_obj_list:
new_obj_dict[obj.get_luid()] = obj
dest_obj_dict = {}
for obj in dest_obj_list:
dest_obj_dict[obj.get_luid()] = obj
# If lengths don't match, they must differ
if len(new_obj_dict) != len(dest_obj_dict):
return False
else:
# If LUIDs don't match, they must differ
new_obj_luids = new_obj_dict.keys()
dest_obj_luids = dest_obj_dict.keys()
new_obj_luids.sort()
dest_obj_luids.sort()
if cmp(new_obj_luids, dest_obj_luids) != 0:
return False
for luid in new_obj_luids:
new_obj = new_obj_dict.get(luid)
dest_obj = dest_obj_dict.get(luid)
return self.are_capabilities_obj_dicts_identical(new_obj.get_capabilities_dict(),
dest_obj.get_capabilities_dict())
@staticmethod
def are_capabilities_obj_dicts_identical(new_obj_dict, dest_obj_dict):
if cmp(new_obj_dict, dest_obj_dict):
return True
else:
return False
# Dict { capability_name : mode } into XML with checks for validity. Set type to 'workbook' or 'datasource'
def build_capabilities_xml_from_dict(self, capabilities_dict, obj_type):
if obj_type not in self.permissionable_objects:
error_text = u'objtype can only be "project", "workbook" or "datasource", was given {}'
raise InvalidOptionException(error_text.format(u'obj_type'))
xml = u'<capabilities>\n'
for cap in capabilities_dict:
# Skip if the capability is set to None
if capabilities_dict[cap] is None:
continue
if capabilities_dict[cap] not in [u'Allow', u'Deny']:
raise InvalidOptionException(u'Capability mode can only be "Allow", "Deny" (case-sensitive)')
if obj_type == u'project':
if cap not in self.available_capabilities[self.api_version][u"project"]:
raise InvalidOptionException(u'{} is not a valid capability for a project'.format(cap))
if obj_type == u'datasource':
# Ignore if not available for datasource
if cap not in self.available_capabilities[self.api_version][u"datasource"]:
self.log(u'{} is not a valid capability for a datasource'.format(cap))
continue
if obj_type == u'workbook':
# Ignore if not available for workbook
if cap not in self.available_capabilities[self.api_version][u"workbook"]:
self.log(u'{} is not a valid capability for a workbook'.format(cap))
continue
xml += u'<capability name="{}" mode="{}" />'.format(cap, capabilities_dict[cap])
xml += u'</capabilities>'
return xml
# Turns lxml that is returned when asking for permissions into a bunch of GranteeCapabilities objects
def convert_capabilities_xml_into_obj_list(self, lxml_obj, obj_type=None):
self.start_log_block()
obj_list = []
xml = lxml_obj.xpath(u'//t:granteeCapabilities', namespaces=self.ns_map)
if len(xml) == 0:
return []
else:
for gcaps in xml:
for tags in gcaps:
# Namespace fun
if tags.tag == u'{}group'.format(self.ns_prefix):
luid = tags.get('id')
gcap_obj = GranteeCapabilities(u'group', luid, obj_type)
self.log(u'group {}'.format(luid))
elif tags.tag == u'{}user'.format(self.ns_prefix):
luid = tags.get('id')
gcap_obj = GranteeCapabilities(u'user', luid, obj_type)
self.log(u'user {}'.format(luid))
elif tags.tag == u'{}capabilities'.format(self.ns_prefix):
for caps in tags:
self.log(caps.get('name') + ' : ' + caps.get('mode'))
gcap_obj.set_capability(caps.get('name'), caps.get('mode'))
obj_list.append(gcap_obj)
self.log(u'Gcap object list has {} items'.format(unicode(len(obj_list))))
self.end_log_block()
return obj_list
class Logger(object):
def __init__(self, filename):
try:
lh = open(filename, 'wb')
self.__log_handle = lh
except IOError:
print u"Error: File '{}' cannot be opened to write for logging".format(filename)
raise
def log(self, l):
cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
log_line = cur_time + " : " + l + "\n"
try:
self.__log_handle.write(log_line.encode('utf8'))
except UnicodeDecodeError as e:
self.__log_handle.write(log_line)
def start_log_block(self):
caller_function_name = sys._getframe(2).f_code.co_name
cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).encode('utf-8')
log_line = u'---------- {} started at {} ----------\n'.format(caller_function_name, cur_time)
self.__log_handle.write(log_line.encode('utf-8'))
def end_log_block(self):
caller_function_name = sys._getframe(2).f_code.co_name
cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).encode('utf-8')
log_line = u'---------- {} ended at {} ------------\n'.format(caller_function_name, cur_time)
self.__log_handle.write(log_line.encode('utf-8'))
def log_uri(self, uri, verb):
self.log(u'Sending {} request via: \n{}'.format(verb, uri))
def log_xml_request(self, xml, verb):
self.log(u'Sending {} request with XML: \n{}'.format(verb, xml))
class TableauRestApi(TableauBase):
# Defines a class that represents a RESTful connection to Tableau Server. Use full URL (http:// or https://)
def __init__(self, server, username, password, site_content_url=""):
super(self.__class__, self).__init__()
if server.find('http') == -1:
raise InvalidOptionException('Server URL must include http:// or https://')
self.__server = server
self._site_content_url = site_content_url
self.__username = username
self.__password = password
self.__token = None # Holds the login token from the Sign In call
self.site_luid = ""
self.user_luid = ""
self.__login_as_user_id = None
self.__last_error = None
self.logger = None
self.__last_response_content_type = None
# All defined in TableauBase superclass
self.__site_roles = self.site_roles
self.__permissionable_objects = self.permissionable_objects
self.__server_to_rest_capability_map = self.server_to_rest_capability_map
#
# Object helpers and setter/getters
#
def get_last_error(self):
self.log(self.__last_error)
return self.__last_error
def set_last_error(self, error):
self.__last_error = error
#
# REST API Helper Methods
#
def build_api_url(self, call, login=False):
if login is True:
return self.__server + u"/api/" + self.api_version + u"/" + call
else:
return self.__server + u"/api/" + self.api_version + u"/sites/" + self.site_luid + u"/" + call
#
# Internal REST API Helpers (mostly XML definitions that are reused between methods)
#
@staticmethod
def __build_site_request_xml(site_name=None, content_url=None, admin_mode=None, user_quota=None,
storage_quota=None, disable_subscriptions=None, state=None):
request = u'<tsRequest><site '
if site_name is not None:
request += u'name="{}" '.format(site_name)
if content_url is not None:
request += u'contentUrl="{}" '.format(content_url)
if admin_mode is not None:
request += u'adminMode="{}" '.format(admin_mode)
if user_quota is not None:
request += u'userQuota="{}" '.format(user_quota)
if state is not None:
request += u'state="{}" '.format(state)
if storage_quota is not None:
request += u'storageQuota="{}" '.format(storage_quota)
if disable_subscriptions is not None:
request += u'disableSubscriptions="{}" '.format(disable_subscriptions)
request += u'/></tsRequest>'
return request
@staticmethod
def __build_connection_update_xml(new_server_address=None, new_server_port=None,
new_connection_username=None, new_connection_password=None):
update_request = u"<tsRequest><connection "
if new_server_address is not None:
update_request += u'serverAddress="{}" '.format(new_server_address)
if new_server_port is not None:
update_request += u'serverPort="{}" '.format(new_server_port)
if new_connection_username is not None:
update_request += u'userName="{}" '.format(new_connection_username)
if new_connection_username is not None:
update_request += u'password="{}"'.format(new_connection_password)
update_request += u"/></tsRequest>"
return update_request
# Runs through the gcap object list, and tries to do a conversion all principals to matching LUIDs on current site
# Use case is replicating settings from one site to another
# Orig_site must be TableauRestApi
def convert_gcap_obj_list_from_orig_site_to_current_site(self, gcap_obj_list, orig_site):
new_gcap_obj_list = []
orig_site_groups = orig_site.query_groups()
orig_site_users = orig_site.query_users()
orig_site_groups_dict = self.convert_xml_list_to_name_id_dict(orig_site_groups)
orig_site_users_dict = self.convert_xml_list_to_name_id_dict(orig_site_users)
new_site_groups = self.query_groups()
new_site_users = self.query_users()
new_site_groups_dict = self.convert_xml_list_to_name_id_dict(new_site_groups)
new_site_users_dict = self.convert_xml_list_to_name_id_dict(new_site_users)
for gcap_obj in gcap_obj_list:
orig_luid = gcap_obj.get_luid()
if gcap_obj.get_obj_type() == 'group':
# Find the name that matches the LUID
try:
orig_name = (key for key, value in orig_site_groups_dict.items() if value == orig_luid).next()
except StopIteration:
raise NoMatchFoundException(u"No matching name for luid {} found on the original site".format(
orig_luid))
new_luid = new_site_groups_dict.get(orig_name)
elif gcap_obj.get_obj_type() == 'user':
# Find the name that matches the LUID
try:
orig_name = (key for key, value in orig_site_users_dict.items() if value == orig_luid).next()
except StopIteration:
raise NoMatchFoundException(u"No matching name for luid {} found on the original site".format(
orig_luid))
new_luid = new_site_users_dict.get(orig_name)
new_gcap_obj = copy.copy(gcap_obj)
if new_luid is None:
raise NoMatchFoundException(u"No matching {} named {} found on the new site".format(
gcap_obj.get_obj_type(), orig_name))
new_gcap_obj.set_luid(new_luid)
new_gcap_obj_list.append(new_gcap_obj)
return new_gcap_obj_list
#
# Factory methods for PublishedContent and GranteeCapabilities objects
#
def get_project_object_by_luid(self, luid):
proj_obj = Project(luid, self, self.version, self.logger)
return proj_obj
def get_workbook_object_by_luid(self, luid):
wb_obj = Workbook(luid, self, self.version, self.logger)
return wb_obj
def get_datasource_object_by_luid(self, luid):
ds_obj = Datasource(luid, self, self.version, self.logger)
return ds_obj
def get_grantee_capabilities_object(self, obj_type, luid, content_type=None):
gcap_obj = GranteeCapabilities(obj_type, luid, content_type, self.version)
return gcap_obj
#
# Sign-in and Sign-out
#
def signin(self):
self.start_log_block()
for version in self.supported_versions:
self.log(u'Trying version {}'.format(version))
self.set_tableau_server_version(version)
if self._site_content_url.lower() in ['default', '']:
login_payload = u'<tsRequest><credentials name="{}" password="{}" >'.format(self.__username, self.__password)
login_payload += u'<site /></credentials></tsRequest>'
else:
login_payload = u'<tsRequest><credentials name="{}" password="{}" >'.format(self.__username, self.__password)
login_payload += u'<site contentUrl="{}" /></credentials></tsRequest>'.format(self._site_content_url)
url = self.build_api_url(u"auth/signin", login=True)
self.log(u'Logging in via: {}'.format(url.encode('utf-8')))
api = RestXmlRequest(url, self.__token, self.logger, ns_map_url=self.ns_map['t'])
api.set_xml_request(login_payload)
api.set_http_verb('post')
self.log(u'Login payload is\n {}'.format(login_payload))
try:
api.request_from_api(0)
# self.log(api.get_raw_response())
xml = api.get_response()
credentials_element = xml.xpath(u'//t:credentials', namespaces=self.ns_map)
self.__token = credentials_element[0].get("token").encode('utf-8')
self.log(u"Token is " + self.__token)
self.site_luid = credentials_element[0].xpath(u"//t:site", namespaces=self.ns_map)[0].get("id").encode('utf-8')
self.user_luid = credentials_element[0].xpath(u"//t:user", namespaces=self.ns_map)[0].get("id").encode('utf-8')
self.log(u"Site ID is " + self.site_luid)
self.log(u"Trying to get workbooks for user to test if API version is really available")
self.query_workbooks()
# if that all works we're good with the version we tried, get out of this loop
break
# If that particular location doesn't exist, move on down the list
except RecoverableHTTPException:
continue
self.end_log_block()
def signout(self):
self.start_log_block()
url = self.build_api_url(u"auth/signout", login=True)
self.log(u'Logging out via: {}'.format(url.encode('utf-8')))
api = RestXmlRequest(url, self.__token, self.logger, ns_map_url=self.ns_map['t'])
api.set_http_verb('post')
api.request_from_api()
self.log(u'Signed out successfully')
self.end_log_block()
#
# HTTP "verb" methods. These actually communicate with the RestXmlRequest object to place the requests
#
# baseline method for any get request. appends to base url
def query_resource(self, url_ending, login=False):
self.start_log_block()
api_call = self.build_api_url(url_ending, login)
api = RestXmlRequest(api_call, self.__token, self.logger, ns_map_url=self.ns_map['t'])
self.log_uri(u'get', api_call)
api.request_from_api()
xml = api.get_response().getroot() # return Element rather than ElementTree
self.end_log_block()
return xml
def send_post_request(self, url):
self.start_log_block()
api = RestXmlRequest(url, self.__token, self.logger, ns_map_url=self.ns_map['t'])
api.set_http_verb(u'post')
api.request_from_api(0)
xml = api.get_response().getroot() # return Element rather than ElementTree
self.end_log_block()
return xml
def send_add_request(self, url, request):
self.start_log_block()
self.log_uri(u'add', url)
api = RestXmlRequest(url, self.__token, self.logger, ns_map_url=self.ns_map['t'])
api.set_xml_request(request)
self.log_xml_request(u'add', request)
api.set_http_verb('post')
api.request_from_api(0) # Zero disables paging, for all non queries
xml = api.get_response().getroot() # return Element rather than ElementTree
self.end_log_block()
return xml
def send_update_request(self, url, request):
self.start_log_block()
self.log_uri(u'update', url)
api = RestXmlRequest(url, self.__token, self.logger, ns_map_url=self.ns_map['t'])
api.set_xml_request(request)
api.set_http_verb(u'put')
self.log_xml_request(u'update', request)
api.request_from_api(0) # Zero disables paging, for all non queries
self.end_log_block()
return api.get_response()
def send_delete_request(self, url):
self.start_log_block()
api = RestXmlRequest(url, self.__token, self.logger, ns_map_url=self.ns_map['t'])
api.set_http_verb(u'delete')
self.log_uri(u'delete', url)
try:
api.request_from_api(0) # Zero disables paging, for all non queries
self.end_log_block()
# Return for counter
return 1
except RecoverableHTTPException as e:
self.log(u'Non fatal HTTP Exception Response {}, Tableau Code {}'.format(e.http_code, e.tableau_error_code))
if e.tableau_error_code in [404003, 404002]:
self.log(u'Delete action did not find the resouce. Consider successful, keep going')
self.end_log_block()
except:
raise
def send_publish_request(self, url, request, boundary_string):
self.start_log_block()
self.log_uri(u'publish', url)
api = RestXmlRequest(url, self.__token, self.logger, ns_map_url=self.ns_map['t'])
api.set_publish_content(request, boundary_string)
api.set_http_verb(u'post')
api.request_from_api(0)
xml = api.get_response().getroot() # return Element rather than ElementTree
self.end_log_block()
return xml
def send_append_request(self, url, request, boundary_string):
self.start_log_block()
self.log_uri(u'append', url)
api = RestXmlRequest(url, self.__token, self.logger, ns_map_url=self.ns_map['t'])
api.set_publish_content(request, boundary_string)
api.set_http_verb(u'put')
api.request_from_api(0)
xml = api.get_response().getroot() # return Element rather than ElementTree
self.end_log_block()
return xml
# Used when the result is not going to be XML and you want to save the raw response as binary
def send_binary_get_request(self, url):
self.start_log_block()
api = RestXmlRequest(url, self.__token, self.logger, ns_map_url=self.ns_map['t'])
self.log_uri(u'binary get', url)
api.set_http_verb(u'get')
api.set_response_type(u'binary')
api.request_from_api(0)
# Set this content type so we can set the file externsion
self.__last_response_content_type = api.get_last_response_content_type()
self.end_log_block()
return api.get_response()
#
# Basic Querying / Get Methods
#
#
# Begin Datasource Querying Methods
#
def query_datasources(self):
self.start_log_block()
datasources = self.query_resource(u"datasources")
self.end_log_block()
return datasources
def query_datasource_by_luid(self, luid):
self.start_log_block()
luid = self.query_resource(u'datasources/{}'.format(luid))
self.end_log_block()
return luid
# Datasources in different projects can have the same 'pretty name'.
def query_datasource_luid_by_name_in_project(self, name, p_name_or_luid=False):
self.start_log_block()
datasources = self.query_datasources()
datasources_with_name = datasources.xpath(u'//t:datasource[@name="{}"]'.format(name), namespaces=self.ns_map)
if len(datasources_with_name) == 0:
self.end_log_block()
raise NoMatchFoundException(u"No datasource found with name {} in any project".format(name))
elif len(datasources_with_name) == 1:
self.end_log_block()
return datasources_with_name[0].get("id")
elif len(datasources_with_name) > 1 and p_name_or_luid is not False:
if self.is_luid(p_name_or_luid):
ds_in_proj = datasources.xpath(u'//t:project[@id="{}"]/..'.format(p_name_or_luid), namespaces=self.ns_map)
else:
ds_in_proj = datasources.xpath(u'//t:project[@name="{}"]/..'.format(p_name_or_luid), namespaces=self.ns_map)
if len(ds_in_proj) == 0:
self.end_log_block()
raise NoMatchFoundException(u"No datasource found with name {} in project {}".format(name, p_name_or_luid))
return ds_in_proj[0].get("id")
# If no project is declared, and
else:
raise MultipleMatchesFoundException(u'More than one datasource found by name {} without a project specified'.format(name))
def query_datasource_by_name_in_project(self, ds_name, p_name_or_luid=False):
self.start_log_block()
ds_luid = self.query_datasource_luid_by_name_in_project(ds_name, p_name_or_luid)
ds = self.query_datasource_by_luid(ds_luid)
self.end_log_block()
return ds
# Tries to guess name or LUID, including for the project. Better to use than just query_datasource
def query_datasource_in_project(self, name_or_luid, p_name_or_luid):
self.start_log_block()
# LUID
if self.is_luid(name_or_luid):
ds = self.query_datasource_by_luid(name_or_luid)
# Name
else:
ds = self.query_datasource_by_name_in_project(name_or_luid, p_name_or_luid)
self.end_log_block()
return ds
# Tries to guess name or LUID, hope there is only one
def query_datasource(self, name_or_luid):
self.start_log_block()
# LUID
if self.is_luid(name_or_luid):
ds = self.query_datasource_by_luid(name_or_luid)
# Name
else:
ds = self.query_datasource_by_name_in_project(name_or_luid)
self.end_log_block()
return ds
def query_datasources_in_project(self, project_name_or_luid):
self.start_log_block()
if self.is_luid(project_name_or_luid):
project_luid = self.query_project_by_luid(project_name_or_luid)
else:
project_luid = self.query_project_luid_by_name(project_name_or_luid)
datasources = self.query_datasources()
# This brings back the datasource itself
ds_in_project = datasources.xpath(u'//t:project[@id="{}"]/..'.format(project_luid), namespaces=self.ns_map)
self.end_log_block()
return ds_in_project
def query_datasource_permissions_by_luid(self, luid):
self.start_log_block()
ds_permissions = self.query_resource(u'datasources/{}/permissions'.format(luid))
self.end_log_block()
return ds_permissions
# This is the best mix of flexibility and precision when called with a project name or luid
def query_datasource_permissions_in_project(self, name_or_luid, p_name_or_luid=False):
self.start_log_block()
if self.is_luid(name_or_luid):
ds_permissions = self.query_datasource_permissions_by_luid(name_or_luid)
else:
ds_permissions = self.query_datasource_permissions_by_name_in_project(name_or_luid, p_name_or_luid)
self.end_log_block()
return ds_permissions
# Preferrable to specify the project in case of multiples
def query_datasource_permissions_by_name_in_project(self, name, p_name_or_luid=False):
self.start_log_block()
datasource_luid = self.query_datasource_luid_by_name_in_project(name, p_name_or_luid)
ds_permissions = self.query_datasource_permissions_by_luid(datasource_luid)
self.end_log_block()
return ds_permissions
# Not as good as query_datasource_permissions_by_name_in_project
def query_datasource_permissions_by_name(self, name):
self.start_log_block()
datasource_luid = self.query_datasource_luid_by_name_in_project(name)
ds_permissions = self.query_datasource_permissions_by_luid(datasource_luid)
self.end_log_block()
return ds_permissions
# Not as good as query_datasource_permissions_in_project
def query_datasource_permissions(self, name_or_luid, p_name_or_luid=False):
self.start_log_block()
if self.is_luid(name_or_luid):
ds_permissions = self.query_datasource_permissions_by_luid(name_or_luid)
else:
ds_permissions = self.query_datasource_permissions_by_name_in_project(name_or_luid, p_name_or_luid)
self.end_log_block()
return ds_permissions
#
# End Datasource Query Methods
#
#
# Start Group Query Methods
#
def query_groups(self):
self.start_log_block()
groups = self.query_resource(u"groups")
self.end_log_block()
return groups
# Simplest to use
def query_group(self, name_or_luid):
self.start_log_block()
if self.is_luid(name_or_luid):
group = self.query_group_by_luid(name_or_luid)
else:
group = self.query_group_by_name(name_or_luid)
self.end_log_block()
return group
# No basic verb for querying a single group, so run a query_groups
def query_group_by_luid(self, group_luid):
self.start_log_block()
groups = self.query_groups()
group = groups.xpath(u'//t:group[@id="{}"]'.format(group_luid), namespaces=self.ns_map)
if len(group) == 1:
self.end_log_block()
return group[0]
else:
self.end_log_block()
raise NoMatchFoundException(u"No group found with luid " + group_luid)
# Groups luckily cannot have the same 'pretty name' on one site
def query_group_luid_by_name(self, name):
self.start_log_block()
groups = self.query_groups()
group = groups.xpath(u'//t:group[@name="{}"]'.format(name), namespaces=self.ns_map)
if len(group) == 1:
self.end_log_block()
return group[0].get("id")
else:
self.end_log_block()
raise NoMatchFoundException(u"No group found with name " + name)
def query_group_by_name(self, name):
self.start_log_block()
group_luid = self.query_group_luid_by_name(name)
group = self.query_group_by_luid(group_luid)
self.end_log_block()
return group
#
# End Group Querying methods
#
#
# Start Project Querying methods
#
def query_projects(self):
self.start_log_block()
projects = self.query_resource(u"projects")