forked from tableau/server-client-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkbooks_endpoint.py
1183 lines (971 loc) · 42.9 KB
/
workbooks_endpoint.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
from email.message import Message
import copy
import io
import logging
import os
from contextlib import closing
from pathlib import Path
from tableauserverclient.helpers.headers import fix_filename
from tableauserverclient.models.permissions_item import PermissionsRule
from tableauserverclient.server.query import QuerySet
from tableauserverclient.server.endpoint.endpoint import QuerysetEndpoint, api, parameter_added_in
from tableauserverclient.server.endpoint.exceptions import (
InternalServerError,
MissingRequiredFieldError,
UnsupportedAttributeError,
)
from tableauserverclient.server.endpoint.permissions_endpoint import _PermissionsEndpoint
from tableauserverclient.server.endpoint.resource_tagger import TaggingMixin
from tableauserverclient.filesys_helpers import (
to_filename,
make_download_path,
get_file_type,
get_file_object_size,
)
from tableauserverclient.helpers import redact_xml
from tableauserverclient.models import WorkbookItem, ConnectionItem, ViewItem, PaginationItem, JobItem, RevisionItem
from tableauserverclient.server import RequestFactory
from typing import (
Optional,
TYPE_CHECKING,
Union,
)
from collections.abc import Iterable, Sequence
if TYPE_CHECKING:
from tableauserverclient.server import Server
from tableauserverclient.server.request_options import RequestOptions, PDFRequestOptions, PPTXRequestOptions
from tableauserverclient.models import DatasourceItem
from tableauserverclient.server.endpoint.schedules_endpoint import AddResponse
io_types_r = (io.BytesIO, io.BufferedReader)
io_types_w = (io.BytesIO, io.BufferedWriter)
# The maximum size of a file that can be published in a single request is 64MB
FILESIZE_LIMIT = 1024 * 1024 * 64 # 64MB
ALLOWED_FILE_EXTENSIONS = ["twb", "twbx"]
from tableauserverclient.helpers.logging import logger
FilePath = Union[str, os.PathLike]
FileObject = Union[io.BufferedReader, io.BytesIO]
FileObjectR = Union[io.BufferedReader, io.BytesIO]
FileObjectW = Union[io.BufferedWriter, io.BytesIO]
PathOrFileR = Union[FilePath, FileObjectR]
PathOrFileW = Union[FilePath, FileObjectW]
class Workbooks(QuerysetEndpoint[WorkbookItem], TaggingMixin[WorkbookItem]):
def __init__(self, parent_srv: "Server") -> None:
super().__init__(parent_srv)
self._permissions = _PermissionsEndpoint(parent_srv, lambda: self.baseurl)
return None
@property
def baseurl(self) -> str:
return f"{self.parent_srv.baseurl}/sites/{self.parent_srv.site_id}/workbooks"
# Get all workbooks on site
@api(version="2.0")
def get(self, req_options: Optional["RequestOptions"] = None) -> tuple[list[WorkbookItem], PaginationItem]:
"""
Queries the server and returns information about the workbooks the site.
Parameters
----------
req_options : RequestOptions, optional
(Optional) You can pass the method a request object that contains
additional parameters to filter the request. For example, if you
were searching for a specific workbook, you could specify the name
of the workbook or the name of the owner.
Returns
-------
Tuple containing one page's worth of workbook items and pagination
information.
"""
logger.info("Querying all workbooks on site")
url = self.baseurl
server_response = self.get_request(url, req_options)
pagination_item = PaginationItem.from_response(server_response.content, self.parent_srv.namespace)
all_workbook_items = WorkbookItem.from_response(server_response.content, self.parent_srv.namespace)
return all_workbook_items, pagination_item
# Get 1 workbook
@api(version="2.0")
def get_by_id(self, workbook_id: str) -> WorkbookItem:
"""
Returns information about the specified workbook on the site.
Parameters
----------
workbook_id : str
The workbook ID.
Returns
-------
WorkbookItem
The workbook item.
"""
if not workbook_id:
error = "Workbook ID undefined."
raise ValueError(error)
logger.info(f"Querying single workbook (ID: {workbook_id})")
url = f"{self.baseurl}/{workbook_id}"
server_response = self.get_request(url)
return WorkbookItem.from_response(server_response.content, self.parent_srv.namespace)[0]
@api(version="2.8")
def refresh(self, workbook_item: Union[WorkbookItem, str], incremental: bool = False) -> JobItem:
"""
Refreshes the extract of an existing workbook.
Parameters
----------
workbook_item : WorkbookItem | str
The workbook item or workbook ID.
incremental: bool
Whether to do a full refresh or incremental refresh of the extract data
Returns
-------
JobItem
The job item.
"""
id_ = getattr(workbook_item, "id", workbook_item)
url = f"{self.baseurl}/{id_}/refresh"
refresh_req = RequestFactory.Task.refresh_req(incremental)
server_response = self.post_request(url, refresh_req)
new_job = JobItem.from_response(server_response.content, self.parent_srv.namespace)[0]
return new_job
# create one or more extracts on 1 workbook, optionally encrypted
@api(version="3.5")
def create_extract(
self,
workbook_item: WorkbookItem,
encrypt: bool = False,
includeAll: bool = True,
datasources: Optional[list["DatasourceItem"]] = None,
) -> JobItem:
"""
Create one or more extracts on 1 workbook, optionally encrypted.
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref.htm#create_extracts_for_workbook
Parameters
----------
workbook_item : WorkbookItem
The workbook item to create extracts for.
encrypt : bool, default False
Set to True to encrypt the extracts.
includeAll : bool, default True
If True, all data sources in the workbook will have an extract
created for them. If False, then a data source must be supplied in
the request.
datasources : list[DatasourceItem] | None
List of DatasourceItem objects for the data sources to create
extracts for. Only required if includeAll is False.
Returns
-------
JobItem
The job item for the extract creation.
"""
id_ = getattr(workbook_item, "id", workbook_item)
url = f"{self.baseurl}/{id_}/createExtract?encrypt={encrypt}"
datasource_req = RequestFactory.Workbook.embedded_extract_req(includeAll, datasources)
server_response = self.post_request(url, datasource_req)
new_job = JobItem.from_response(server_response.content, self.parent_srv.namespace)[0]
return new_job
# delete all the extracts on 1 workbook
@api(version="3.3")
def delete_extract(self, workbook_item: WorkbookItem, includeAll: bool = True, datasources=None) -> JobItem:
"""
Delete all extracts of embedded datasources on 1 workbook.
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref.htm#delete_extracts_from_workbook
Parameters
----------
workbook_item : WorkbookItem
The workbook item to delete extracts from.
includeAll : bool, default True
If True, all data sources in the workbook will have their extracts
deleted. If False, then a data source must be supplied in the
request.
datasources : list[DatasourceItem] | None
List of DatasourceItem objects for the data sources to delete
extracts from. Only required if includeAll is False.
Returns
-------
JobItem
"""
id_ = getattr(workbook_item, "id", workbook_item)
url = f"{self.baseurl}/{id_}/deleteExtract"
datasource_req = RequestFactory.Workbook.embedded_extract_req(includeAll, datasources)
server_response = self.post_request(url, datasource_req)
new_job = JobItem.from_response(server_response.content, self.parent_srv.namespace)[0]
return new_job
# Delete 1 workbook by id
@api(version="2.0")
def delete(self, workbook_id: str) -> None:
"""
Deletes a workbook with the specified ID.
Parameters
----------
workbook_id : str
The workbook ID.
Returns
-------
None
"""
if not workbook_id:
error = "Workbook ID undefined."
raise ValueError(error)
url = f"{self.baseurl}/{workbook_id}"
self.delete_request(url)
logger.info(f"Deleted single workbook (ID: {workbook_id})")
# Update workbook
@api(version="2.0")
@parameter_added_in(include_view_acceleration_status="3.22")
def update(
self,
workbook_item: WorkbookItem,
include_view_acceleration_status: bool = False,
) -> WorkbookItem:
"""
Modifies an existing workbook. Use this method to change the owner or
the project that the workbook belongs to, or to change whether the
workbook shows views in tabs. The workbook item must include the
workbook ID and overrides the existing settings.
See https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_workbooks_and_views.htm#update_workbook
for a list of fields that can be updated.
Parameters
----------
workbook_item : WorkbookItem
The workbook item to update. ID is required. Other fields are
optional. Any fields that are not specified will not be changed.
include_view_acceleration_status : bool, default False
Set to True to include the view acceleration status in the response.
Returns
-------
WorkbookItem
The updated workbook item.
"""
if not workbook_item.id:
error = "Workbook item missing ID. Workbook must be retrieved from server first."
raise MissingRequiredFieldError(error)
self.update_tags(workbook_item)
# Update the workbook itself
url = f"{self.baseurl}/{workbook_item.id}"
if include_view_acceleration_status:
url += "?includeViewAccelerationStatus=True"
update_req = RequestFactory.Workbook.update_req(workbook_item, self.parent_srv)
server_response = self.put_request(url, update_req)
logger.info(f"Updated workbook item (ID: {workbook_item.id})")
updated_workbook = copy.copy(workbook_item)
return updated_workbook._parse_common_tags(server_response.content, self.parent_srv.namespace)
# Update workbook_connection
@api(version="2.3")
def update_connection(self, workbook_item: WorkbookItem, connection_item: ConnectionItem) -> ConnectionItem:
"""
Updates a workbook connection information (server addres, server port,
user name, and password).
The workbook connections must be populated before the strings can be
updated.
Rest API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref.htm#update_workbook_connection
Parameters
----------
workbook_item : WorkbookItem
The workbook item to update.
connection_item : ConnectionItem
The connection item to update.
Returns
-------
ConnectionItem
The updated connection item.
"""
url = f"{self.baseurl}/{workbook_item.id}/connections/{connection_item.id}"
update_req = RequestFactory.Connection.update_req(connection_item)
server_response = self.put_request(url, update_req)
connection = ConnectionItem.from_response(server_response.content, self.parent_srv.namespace)[0]
logger.info(f"Updated workbook item (ID: {workbook_item.id} & connection item {connection_item.id})")
return connection
# Download workbook contents with option of passing in filepath
@api(version="2.0")
@parameter_added_in(no_extract="2.5")
@parameter_added_in(include_extract="2.5")
def download(
self,
workbook_id: str,
filepath: Optional[PathOrFileW] = None,
include_extract: bool = True,
) -> PathOrFileW:
"""
Downloads a workbook to the specified directory (optional).
Parameters
----------
workbook_id : str
The workbook ID.
filepath : Path or File object, optional
Downloads the file to the location you specify. If no location is
specified, the file is downloaded to the current working directory.
The default is Filepath=None.
include_extract : bool, default True
Set to False to exclude the extract from the download. The default
is True.
Returns
-------
Path or File object
The path to the downloaded workbook or the file object.
Raises
------
ValueError
If the workbook ID is not defined.
"""
return self.download_revision(
workbook_id,
None,
filepath,
include_extract,
)
# Get all views of workbook
@api(version="2.0")
def populate_views(self, workbook_item: WorkbookItem, usage: bool = False) -> None:
"""
Populates (or gets) a list of views for a workbook.
You must first call this method to populate views before you can iterate
through the views.
This method retrieves the view information for the specified workbook.
The REST API is designed to return only the information you ask for
explicitly. When you query for all the workbooks, the view information
is not included. Use this method to retrieve the views. The method adds
the list of views to the workbook item (workbook_item.views). This is a
list of ViewItem.
Parameters
----------
workbook_item : WorkbookItem
The workbook item to populate views for.
usage : bool, default False
Set to True to include usage statistics for each view.
Returns
-------
None
Raises
------
MissingRequiredFieldError
If the workbook item is missing an ID.
"""
if not workbook_item.id:
error = "Workbook item missing ID. Workbook must be retrieved from server first."
raise MissingRequiredFieldError(error)
def view_fetcher() -> list[ViewItem]:
return self._get_views_for_workbook(workbook_item, usage)
workbook_item._set_views(view_fetcher)
logger.info(f"Populated views for workbook (ID: {workbook_item.id})")
def _get_views_for_workbook(self, workbook_item: WorkbookItem, usage: bool) -> list[ViewItem]:
url = f"{self.baseurl}/{workbook_item.id}/views"
if usage:
url += "?includeUsageStatistics=true"
server_response = self.get_request(url)
views = ViewItem.from_response(
server_response.content,
self.parent_srv.namespace,
workbook_id=workbook_item.id,
)
return views
# Get all connections of workbook
@api(version="2.0")
def populate_connections(self, workbook_item: WorkbookItem) -> None:
"""
Populates a list of data source connections for the specified workbook.
You must populate connections before you can iterate through the
connections.
This method retrieves the data source connection information for the
specified workbook. The REST API is designed to return only the
information you ask for explicitly. When you query all the workbooks,
the data source connection information is not included. Use this method
to retrieve the connection information for any data sources used by the
workbook. The method adds the list of data connections to the workbook
item (workbook_item.connections). This is a list of ConnectionItem.
REST API docs: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref.htm#query_workbook_connections
Parameters
----------
workbook_item : WorkbookItem
The workbook item to populate connections for.
Returns
-------
None
Raises
------
MissingRequiredFieldError
If the workbook item is missing an ID.
"""
if not workbook_item.id:
error = "Workbook item missing ID. Workbook must be retrieved from server first."
raise MissingRequiredFieldError(error)
def connection_fetcher():
return self._get_workbook_connections(workbook_item)
workbook_item._set_connections(connection_fetcher)
logger.info(f"Populated connections for workbook (ID: {workbook_item.id})")
def _get_workbook_connections(
self, workbook_item: WorkbookItem, req_options: Optional["RequestOptions"] = None
) -> list[ConnectionItem]:
url = f"{self.baseurl}/{workbook_item.id}/connections"
server_response = self.get_request(url, req_options)
connections = ConnectionItem.from_response(server_response.content, self.parent_srv.namespace)
return connections
@api(version="3.4")
def populate_pdf(self, workbook_item: WorkbookItem, req_options: Optional["PDFRequestOptions"] = None) -> None:
"""
Populates the PDF for the specified workbook item. Get the pdf of the
entire workbook if its tabs are enabled, pdf of the default view if its
tabs are disabled.
This method populates a PDF with image(s) of the workbook view(s) you
specify.
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref.htm#download_workbook_pdf
Parameters
----------
workbook_item : WorkbookItem
The workbook item to populate the PDF for.
req_options : PDFRequestOptions, optional
(Optional) You can pass in request options to specify the page type
and orientation of the PDF content, as well as the maximum age of
the PDF rendered on the server. See PDFRequestOptions class for more
details.
Returns
-------
None
Raises
------
MissingRequiredFieldError
If the workbook item is missing an ID.
"""
if not workbook_item.id:
error = "Workbook item missing ID."
raise MissingRequiredFieldError(error)
def pdf_fetcher() -> bytes:
return self._get_wb_pdf(workbook_item, req_options)
if not self.parent_srv.check_at_least_version("3.23") and req_options is not None:
if req_options.view_filters or req_options.view_parameters:
raise UnsupportedAttributeError("view_filters and view_parameters are only supported in 3.23+")
if req_options.viz_height or req_options.viz_width:
raise UnsupportedAttributeError("viz_height and viz_width are only supported in 3.23+")
workbook_item._set_pdf(pdf_fetcher)
logger.info(f"Populated pdf for workbook (ID: {workbook_item.id})")
def _get_wb_pdf(self, workbook_item: WorkbookItem, req_options: Optional["PDFRequestOptions"]) -> bytes:
url = f"{self.baseurl}/{workbook_item.id}/pdf"
server_response = self.get_request(url, req_options)
pdf = server_response.content
return pdf
@api(version="3.8")
def populate_powerpoint(
self, workbook_item: WorkbookItem, req_options: Optional["PPTXRequestOptions"] = None
) -> None:
"""
Populates the PowerPoint for the specified workbook item.
This method populates a PowerPoint with image(s) of the workbook view(s) you
specify.
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref.htm#download_workbook_powerpoint
Parameters
----------
workbook_item : WorkbookItem
The workbook item to populate the PDF for.
req_options : RequestOptions, optional
(Optional) You can pass in request options to specify the maximum
number of minutes a workbook .pptx will be cached before being
refreshed. To prevent multiple .pptx requests from overloading the
server, the shortest interval you can set is one minute. There is no
maximum value, but the server job enacting the caching action may
expire before a long cache period is reached.
Returns
-------
None
Raises
------
MissingRequiredFieldError
If the workbook item is missing an ID.
"""
if not workbook_item.id:
error = "Workbook item missing ID."
raise MissingRequiredFieldError(error)
def pptx_fetcher() -> bytes:
return self._get_wb_pptx(workbook_item, req_options)
workbook_item._set_powerpoint(pptx_fetcher)
logger.info(f"Populated powerpoint for workbook (ID: {workbook_item.id})")
def _get_wb_pptx(self, workbook_item: WorkbookItem, req_options: Optional["PPTXRequestOptions"]) -> bytes:
url = f"{self.baseurl}/{workbook_item.id}/powerpoint"
server_response = self.get_request(url, req_options)
pptx = server_response.content
return pptx
# Get preview image of workbook
@api(version="2.0")
def populate_preview_image(self, workbook_item: WorkbookItem) -> None:
"""
This method gets the preview image (thumbnail) for the specified workbook item.
This method uses the workbook's ID to get the preview image. The method
adds the preview image to the workbook item (workbook_item.preview_image).
Parameters
----------
workbook_item : WorkbookItem
The workbook item to populate the preview image for.
Returns
-------
None
Raises
------
MissingRequiredFieldError
If the workbook item is missing an ID.
"""
if not workbook_item.id:
error = "Workbook item missing ID. Workbook must be retrieved from server first."
raise MissingRequiredFieldError(error)
def image_fetcher() -> bytes:
return self._get_wb_preview_image(workbook_item)
workbook_item._set_preview_image(image_fetcher)
logger.info(f"Populated preview image for workbook (ID: {workbook_item.id})")
def _get_wb_preview_image(self, workbook_item: WorkbookItem) -> bytes:
url = f"{self.baseurl}/{workbook_item.id}/previewImage"
server_response = self.get_request(url)
preview_image = server_response.content
return preview_image
@api(version="2.0")
def populate_permissions(self, item: WorkbookItem) -> None:
"""
Populates the permissions for the specified workbook item.
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_permissions.htm#query_workbook_permissions
Parameters
----------
item : WorkbookItem
The workbook item to populate permissions for.
Returns
-------
None
"""
self._permissions.populate(item)
@api(version="2.0")
def update_permissions(self, resource: WorkbookItem, rules: list[PermissionsRule]) -> list[PermissionsRule]:
"""
Updates the permissions for the specified workbook item. The method
replaces the existing permissions with the new permissions. Any missing
permissions are removed.
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_permissions.htm#replace_permissions_for_content
Parameters
----------
resource : WorkbookItem
The workbook item to update permissions for.
rules : list[PermissionsRule]
A list of permissions rules to apply to the workbook item.
Returns
-------
list[PermissionsRule]
The updated permissions rules.
"""
return self._permissions.update(resource, rules)
@api(version="2.0")
def delete_permission(self, item: WorkbookItem, capability_item: PermissionsRule) -> None:
"""
Deletes a single permission rule from the specified workbook item.
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_permissions.htm#delete_workbook_permission
Parameters
----------
item : WorkbookItem
The workbook item to delete the permission from.
capability_item : PermissionsRule
The permission rule to delete.
Returns
-------
None
"""
return self._permissions.delete(item, capability_item)
@api(version="2.0")
@parameter_added_in(as_job="3.0")
@parameter_added_in(connections="2.8")
def publish(
self,
workbook_item: WorkbookItem,
file: PathOrFileR,
mode: str,
connections: Optional[Sequence[ConnectionItem]] = None,
as_job: bool = False,
skip_connection_check: bool = False,
parameters=None,
):
"""
Publish a workbook to the specified site.
Note: The REST API cannot automatically include extracts or other
resources that the workbook uses. Therefore, a .twb file that uses data
from an Excel or csv file on a local computer cannot be published,
unless you package the data and workbook in a .twbx file, or publish the
data source separately.
For workbooks that are larger than 64 MB, the publish method
automatically takes care of chunking the file in parts for uploading.
Using this method is considerably more convenient than calling the
publish REST APIs directly.
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_workbooks_and_views.htm#publish_workbook
Parameters
----------
workbook_item : WorkbookItem
The workbook_item specifies the workbook you are publishing. When
you are adding a workbook, you need to first create a new instance
of a workbook_item that includes a project_id of an existing
project. The name of the workbook will be the name of the file,
unless you also specify a name for the new workbook when you create
the instance.
file : Path or File object
The file path or file object of the workbook to publish. When
providing a file object, you must also specifiy the name of the
workbook in your instance of the workbook_itemworkbook_item , as
the name cannot be derived from the file name.
mode : str
Specifies whether you are publishing a new workbook (CreateNew) or
overwriting an existing workbook (Overwrite). You cannot appending
workbooks. You can also use the publish mode attributes, for
example: TSC.Server.PublishMode.Overwrite.
connections : list[ConnectionItem] | None
List of ConnectionItems objects for the connections created within
the workbook.
as_job : bool, default False
Set to True to run the upload as a job (asynchronous upload). If set
to True a job will start to perform the publishing process and a Job
object is returned. Defaults to False.
skip_connection_check : bool, default False
Set to True to skip connection check at time of upload. Publishing
will succeed but unchecked connection issues may result in a
non-functioning workbook. Defaults to False.
Raises
------
OSError
If the file path does not lead to an existing file.
ServerResponseError
If the server response is not successful.
TypeError
If the file is not a file path or file object.
ValueError
If the file extension is not supported
ValueError
If the mode is invalid.
ValueError
Workbooks cannot be appended.
Returns
-------
WorkbookItem | JobItem
The workbook item or job item that was published.
"""
if isinstance(file, (str, os.PathLike)):
if not os.path.isfile(file):
error = "File path does not lead to an existing file."
raise OSError(error)
filename = os.path.basename(file)
file_extension = os.path.splitext(filename)[1][1:]
file_size = os.path.getsize(file)
# If name is not defined, grab the name from the file to publish
if not workbook_item.name:
workbook_item.name = os.path.splitext(filename)[0]
if file_extension not in ALLOWED_FILE_EXTENSIONS:
error = "Only {} files can be published as workbooks.".format(", ".join(ALLOWED_FILE_EXTENSIONS))
raise ValueError(error)
elif isinstance(file, io_types_r):
if not workbook_item.name:
error = "Workbook item must have a name when passing a file object"
raise ValueError(error)
file_type = get_file_type(file)
if file_type == "zip":
file_extension = "twbx"
elif file_type == "xml":
file_extension = "twb"
else:
error = f"Unsupported file type {file_type}!"
raise ValueError(error)
# Generate filename for file object.
# This is needed when publishing the workbook in a single request
filename = f"{workbook_item.name}.{file_extension}"
file_size = get_file_object_size(file)
else:
raise TypeError("file should be a filepath or file object.")
if not hasattr(self.parent_srv.PublishMode, mode):
error = "Invalid mode defined."
raise ValueError(error)
# Construct the url with the defined mode
url = f"{self.baseurl}?workbookType={file_extension}"
if mode == self.parent_srv.PublishMode.Overwrite:
url += f"&{mode.lower()}=true"
elif mode == self.parent_srv.PublishMode.Append:
error = "Workbooks cannot be appended."
raise ValueError(error)
if as_job:
url += "&{}=true".format("asJob")
if skip_connection_check:
url += "&{}=true".format("skipConnectionCheck")
# Determine if chunking is required (64MB is the limit for single upload method)
if file_size >= FILESIZE_LIMIT:
logger.info(f"Publishing {workbook_item.name} to server with chunking method (workbook over 64MB)")
upload_session_id = self.parent_srv.fileuploads.upload(file)
url = f"{url}&uploadSessionId={upload_session_id}"
xml_request, content_type = RequestFactory.Workbook.publish_req_chunked(
workbook_item,
connections=connections,
)
else:
logger.info(f"Publishing {filename} to server")
if isinstance(file, (str, Path)):
with open(file, "rb") as f:
file_contents = f.read()
elif isinstance(file, io_types_r):
file_contents = file.read()
else:
raise TypeError("file should be a filepath or file object.")
xml_request, content_type = RequestFactory.Workbook.publish_req(
workbook_item,
filename,
file_contents,
connections=connections,
)
logger.debug(f"Request xml: {redact_xml(xml_request[:1000])} ")
# Send the publishing request to server
try:
server_response = self.post_request(url, xml_request, content_type, parameters)
except InternalServerError as err:
if err.code == 504 and not as_job:
err.content = "Timeout error while publishing. Please use asynchronous publishing to avoid timeouts."
raise err
if as_job:
new_job = JobItem.from_response(server_response.content, self.parent_srv.namespace)[0]
logger.info(f"Published {workbook_item.name} (JOB_ID: {new_job.id}")
return new_job
else:
new_workbook = WorkbookItem.from_response(server_response.content, self.parent_srv.namespace)[0]
logger.info(f"Published {workbook_item.name} (ID: {new_workbook.id})")
return new_workbook
# Populate workbook item's revisions
@api(version="2.3")
def populate_revisions(self, workbook_item: WorkbookItem) -> None:
"""
Populates (or gets) a list of revisions for a workbook.
You must first call this method to populate revisions before you can
iterate through the revisions.
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_workbooks_and_views.htm#get_workbook_revisions
Parameters
----------
workbook_item : WorkbookItem
The workbook item to populate revisions for.
Returns
-------
None
Raises
------
MissingRequiredFieldError
If the workbook item is missing an ID.
"""
if not workbook_item.id:
error = "Workbook item missing ID. Workbook must be retrieved from server first."
raise MissingRequiredFieldError(error)
def revisions_fetcher():
return self._get_workbook_revisions(workbook_item)
workbook_item._set_revisions(revisions_fetcher)
logger.info(f"Populated revisions for workbook (ID: {workbook_item.id})")
def _get_workbook_revisions(
self, workbook_item: WorkbookItem, req_options: Optional["RequestOptions"] = None
) -> list[RevisionItem]:
url = f"{self.baseurl}/{workbook_item.id}/revisions"
server_response = self.get_request(url, req_options)
revisions = RevisionItem.from_response(server_response.content, self.parent_srv.namespace, workbook_item)
return revisions
# Download 1 workbook revision by revision number
@api(version="2.3")
def download_revision(
self,
workbook_id: str,
revision_number: Optional[str],
filepath: Optional[PathOrFileW] = None,
include_extract: bool = True,
) -> PathOrFileW:
"""
Downloads a workbook revision to the specified directory (optional).
REST API: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_workbooks_and_views.htm#download_workbook_revision
Parameters
----------
workbook_id : str
The workbook ID.
revision_number : str | None
The revision number of the workbook. If None, the latest revision is
downloaded.
filepath : Path or File object, optional
Downloads the file to the location you specify. If no location is
specified, the file is downloaded to the current working directory.
The default is Filepath=None.
include_extract : bool, default True
Set to False to exclude the extract from the download. The default
is True.
Returns
-------
Path or File object
The path to the downloaded workbook or the file object.
Raises
------
ValueError
If the workbook ID is not defined.
"""
if not workbook_id:
error = "Workbook ID undefined."
raise ValueError(error)
if revision_number is None:
url = f"{self.baseurl}/{workbook_id}/content"
else:
url = f"{self.baseurl}/{workbook_id}/revisions/{revision_number}/content"
if not include_extract:
url += "?includeExtract=False"
with closing(self.get_request(url, parameters={"stream": True})) as server_response:
m = Message()
m["Content-Disposition"] = server_response.headers["Content-Disposition"]
params = m.get_filename(failobj="")
if isinstance(filepath, io_types_w):
for chunk in server_response.iter_content(1024): # 1KB
filepath.write(chunk)
return_path = filepath
else:
params = fix_filename(params)
filename = to_filename(os.path.basename(params))
download_path = make_download_path(filepath, filename)
with open(download_path, "wb") as f:
for chunk in server_response.iter_content(1024): # 1KB
f.write(chunk)
return_path = os.path.abspath(download_path)
logger.info(f"Downloaded workbook revision {revision_number} to {return_path} (ID: {workbook_id})")
return return_path
@api(version="2.3")
def delete_revision(self, workbook_id: str, revision_number: str) -> None:
"""
Deletes a specific revision from a workbook on Tableau Server.