-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathwiki.py
423 lines (342 loc) · 16.1 KB
/
wiki.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
from .discussion import DSSObjectDiscussions
from ..utils import DataikuException
import sys
import copy
import re
if sys.version_info >= (3,0):
import urllib.parse
dku_quote_fn = urllib.parse.quote
else:
import urllib
dku_quote_fn = urllib.quote
class DSSWiki(object):
"""
A handle to manage the wiki of a project
.. important::
Do not instantiate this class directly, instead use :meth:`dataikuapi.dss.project.DSSProject.get_wiki`
"""
def __init__(self, client, project_key):
self.client = client
self.project_key = project_key
def get_settings(self):
"""
Get wiki settings
:returns: a handle to manage the wiki settings (taxonomy, home article)
:rtype: :class:`dataikuapi.dss.wiki.DSSWikiSettings`
"""
return DSSWikiSettings(self.client, self.project_key, self.client._perform_json("GET", "/projects/%s/wiki/" % (self.project_key)))
def get_article(self, article_id_or_name):
"""
Get a wiki article
:param str article_id_or_name: reference to the article, it can be its ID or its name
:returns: a handle to manage the Article
:rtype: :class:`dataikuapi.dss.wiki.DSSWikiArticle`
"""
return DSSWikiArticle(self.client, self.project_key, article_id_or_name)
def __flatten_taxonomy__(self, taxonomy):
"""
Private recursive method to get the flatten list of article IDs from the taxonomy
:param list taxonomy:
:returns: list of articles
:rtype: list of :class:`dataikuapi.dss.wiki.DSSWikiArticle`
"""
article_list = []
for article in taxonomy:
article_list.append(self.get_article(article['id']))
article_list += self.__flatten_taxonomy__(article['children'])
return article_list
def list_articles(self):
"""
Get a list of all the articles in form of :class:`dataikuapi.dss.wiki.DSSWikiArticle` objects
:returns: list of articles
:rtype: list of :class:`dataikuapi.dss.wiki.DSSWikiArticle`
"""
return self.__flatten_taxonomy__(self.get_settings().get_taxonomy())
def create_article(self, article_name, parent_id=None, content=None):
"""
Create a wiki article and return a handle to interact with it.
:param str article_name: the article name
:param str parent_id: the parent article ID (or None if the article has to be at root level, defaults to **None**)
:param str content: the article content (defaults to **None**)
:returns: the created article
:rtype: :class:`dataikuapi.dss.wiki.DSSWikiArticle`
"""
body = {
"projectKey": self.project_key,
"name": article_name,
"parent": parent_id
}
result = self.client._perform_json("POST", "/projects/%s/wiki/" % (self.project_key), body=body)
article = DSSWikiArticle(self.client, self.project_key, result['article']['id'])
# set article content if given
if content is not None:
article_data = article.get_data()
article_data.set_body(content)
article_data.save()
return article
def get_export_stream(self, paper_size="A4", export_attachment=False):
"""
Download the whole wiki of the project in PDF format as a binary stream.
.. warning::
You need to close the stream after download. Failure to do so will result in the DSSClient becoming unusable.
:param str paper_size: the format of the exported page, can be one of 'A4', 'A3', 'US_LETTER' or 'LEDGER' (defaults to **A4**)
:param bool export_attachment: export the attachments of the article(s) in addition to the pdf in a zip file (defaults to **False**)
:returns: the exported pdf or zip file as a stream
"""
body = {
"paperSize": paper_size,
"exportAttachments": export_attachment
}
return self.client._perform_raw("POST", "/projects/%s/wiki/actions/export" % (self.project_key), body=body)
def export_to_file(self, path, paper_size="A4", export_attachment=False):
"""
Download the whole wiki of the project in PDF format into the given output file.
:param str path: the path of the file where the pdf or zip file will be downloaded
:param str paper_size: the format of the exported page, can be one of 'A4', 'A3', 'US_LETTER' or 'LEDGER' (defaults to **A4**)
:param bool export_attachment: export the attachments of the article(s) in addition to the pdf in a zip file (defaults to **False**)
"""
with self.get_export_stream(paper_size=paper_size, export_attachment=export_attachment) as stream:
with open(path, 'wb') as f:
for chunk in stream.iter_content(chunk_size=10000):
if chunk:
f.write(chunk)
f.flush()
class DSSWikiSettings(object):
"""
Global settings for the wiki, including taxonomy. Call save() to save
"""
def __init__(self, client, project_key, settings):
"""Do not instantiate this class directly, instead use :meth:`dataikuapi.dss.wiki.DSSWiki.get_settings`"""
self.client = client
self.project_key = project_key
self.settings = settings
def get_taxonomy(self):
"""
Get the taxonomy.
The taxonomy is an array listing at top level the root article IDs and their children in a tree format.
Every existing article of the wiki has to be in the taxonomy once and only once.
For instance:
.. code-block:: python
[
{
'id': 'article1',
'children': []
},
{
'id': 'article2',
'children': [
{
'id': 'article3',
'children': []
}
]
}
]
.. note ::
Note that this is a direct reference, not a copy, so modifications to the returned object will be reflected when saving
:returns: The taxonomy
:rtype: list
"""
return self.settings["taxonomy"] if "taxonomy" in self.settings else []
def __retrieve_article_in_taxonomy__(self, taxonomy, article_id, remove=False):
"""
Private recursive method that get the sub tree structure from the taxonomy for a specific article
:param list taxonomy: the current level of taxonomy
:param str article_id: the article to retrieve
:param bool remove: either remove the sub tree structure or not (defaults to **False**)
:returns: the sub tree structure at a specific article level
:rtype: dict
"""
idx = 0
for tax_article in taxonomy:
if tax_article["id"] == article_id:
ret = taxonomy.pop(idx) if remove else taxonomy[idx]
return ret
children_ret = self.__retrieve_article_in_taxonomy__(tax_article["children"], article_id, remove)
if children_ret is not None:
return children_ret
idx += 1
return None
def move_article_in_taxonomy(self, article_id, parent_article_id=None):
"""
An helper to update the taxonomy by moving an article with its children as a child of another article
:param str article_id: the main article ID
:param str parent_article_id: the new parent article ID or None for root level (defaults to **None**)
"""
old_taxonomy = copy.deepcopy(self.settings["taxonomy"])
tax_article = self.__retrieve_article_in_taxonomy__(self.settings["taxonomy"], article_id, True)
if tax_article is None:
raise DataikuException("Article not found: %s" % (article_id))
if parent_article_id is None:
self.settings["taxonomy"].append(tax_article)
else:
tax_parent_article = self.__retrieve_article_in_taxonomy__(self.settings["taxonomy"], parent_article_id, False)
if tax_parent_article is None:
self.settings["taxonomy"] = old_taxonomy
raise DataikuException("Parent article not found (or is one of the article descendants): %s" % (parent_article_id))
tax_parent_article["children"].append(tax_article)
def set_taxonomy(self, taxonomy):
"""
Set the taxonomy
:param list taxonomy: the taxonomy
"""
self.settings["taxonomy"] = taxonomy
def get_home_article_id(self):
"""
Get the home article ID
:returns: The home article ID
:rtype: str
"""
return self.settings["homeArticleId"] if "homeArticleId" in self.settings else None
def set_home_article_id(self, home_article_id):
"""
Set the home article ID
:param str home_article_id: the home article ID
"""
self.settings["homeArticleId"] = home_article_id
def save(self):
"""
Save the current settings to the backend
"""
self.settings = self.client._perform_json("PUT", "/projects/%s/wiki/" % (self.project_key), body=self.settings)
class DSSWikiArticle(object):
"""
A handle to manage an article
"""
def __init__(self, client, project_key, article_id_or_name):
"""Do not instantiate this class directly, instead use :meth:`dataikuapi.dss.wiki.DSSWiki.get_article`"""
self.client = client
self.project_key = project_key
# Retrieve the real article id
article_data = self.client._perform_json("GET", "/projects/%s/wiki/%s" % (project_key, article_id_or_name))
self.article_id = article_data["article"]['id']
# encode in UTF-8 if its python2 and unicode
if sys.version_info < (3,0) and isinstance(self.article_id, unicode):
self.article_id = self.article_id.encode('utf-8')
def get_data(self):
"""
Get article data handle
:returns: the article data handle
:rtype: :class:`dataikuapi.dss.wiki.DSSWikiArticleData`
"""
article_data = self.client._perform_json("GET", "/projects/%s/wiki/%s" % (self.project_key, self.article_id))
return DSSWikiArticleData(self.client, self.project_key, self.article_id, article_data)
def upload_attachement(self, fp, filename):
"""
Upload and attach a file to the article.
.. note ::
Note that the type of file will be determined by the filename extension
:param file fp: A file-like object that represents the upload file
:param str filename: The attachement filename
"""
clean_filename = re.sub(r'[^A-Za-z0-9 ._-]+', '', filename)
self.client._perform_json("POST", "/projects/%s/wiki/%s/upload" % (self.project_key, dku_quote_fn(self.article_id)), files={"file":(clean_filename, fp)})
def get_uploaded_file(self, upload_id):
"""
Download an attachment of the article
.. warning::
You need to close the stream after download. Failure to do so will result in the DSSClient becoming unusable.
:param str upload_id: The attachement upload id
:returns: The attachment file as a stream
:rtype: :class:`requests.Response`
"""
return self.client._perform_raw("GET", "/projects/%s/wiki/%s/uploads/%s" % (self.project_key, self.article_id, upload_id))
def get_export_stream(self, paper_size="A4", export_children=False, export_attachment=False):
"""
Download the article in PDF format as a binary stream.
.. warning::
You need to close the stream after download. Failure to do so will result in the DSSClient becoming unusable.
:param str paper_size: the format of the exported page, can be one of 'A4', 'A3', 'US_LETTER' or 'LEDGER' (defaults to **A4**)
:param bool export_children: export the children of the article in the pdf (defaults to **False**)
:param bool export_attachment: export the attachments of the article(s) in addition to the pdf in a zip file (defaults to **False**)
:returns: the exported pdf or zip file as a stream
:rtype: :class:`requests.Response`
"""
body = {
"paperSize": paper_size,
"exportChildren": export_children,
"exportAttachments": export_attachment
}
return self.client._perform_raw("POST", "/projects/%s/wiki/%s/actions/export" % (self.project_key, self.article_id), body=body)
def export_to_file(self, path, paper_size="A4", export_children=False, export_attachment=False):
"""
Download the article in PDF format into the given output file.
:param str path: the path of the file where the pdf or zip file will be downloaded
:param str paper_size: the format of the exported page, can be one of 'A4', 'A3', 'US_LETTER' or 'LEDGER' (defaults to **A4**)
:param bool export_children: export the children of the article in the pdf (defaults to **False**)
:param bool export_attachment: export the attachments of the article(s) in addition to the pdf in a zip file (defaults to **False**)
"""
with self.get_export_stream(paper_size=paper_size, export_children=export_children, export_attachment=export_attachment) as stream:
with open(path, 'wb') as f:
for chunk in stream.iter_content(chunk_size=10000):
if chunk:
f.write(chunk)
f.flush()
def delete(self):
"""
Delete the article
"""
self.client._perform_empty("DELETE", "/projects/%s/wiki/%s" % (self.project_key, dku_quote_fn(self.article_id)))
def get_object_discussions(self):
"""
Get a handle to manage discussions on the article
:returns: the handle to manage discussions
:rtype: :class:`dataikuapi.dss.wiki.DSSObjectDiscussions`
"""
return DSSObjectDiscussions(self.client, self.project_key, "ARTICLE", self.article_id)
class DSSWikiArticleData(object):
"""
A handle to manage an article
"""
def __init__(self, client, project_key, article_id, article_data):
"""Do not instantiate this class directly, instead use :meth:`dataikuapi.dss.wiki.DSSWikiArticle.get_data`"""
self.client = client
self.project_key = project_key
self.article_id = article_id # don't need to check unicode here (already done in DSSWikiArticle)
self.article_data = article_data
def get_body(self):
"""
Get the markdown body as string
:returns: the article body
:rtype: str
"""
return self.article_data["payload"] if "payload" in self.article_data else None
def set_body(self, content):
"""
Set the markdown body
:param str content: the article content
"""
self.article_data["payload"] = content
def get_metadata(self):
"""
Get the article and attachment metadata
.. note ::
Note that this is a direct reference, not a copy, so modifications to the returned object will be reflected when saving
:returns: the article metadata
:rtype: dict
"""
return self.article_data["article"] if "article" in self.article_data else None
def set_metadata(self, metadata):
"""
Set the article metadata
:param dict metadata: the article metadata
"""
self.article_data["article"] = metadata
def get_name(self):
"""
Get the article name
:returns: the article name
:rtype: str
"""
return self.article_data["article"]["name"]
def set_name(self, name):
"""
Set the article name
:param str name: the article name
"""
self.article_data["article"]["name"] = name
def save(self):
"""
Save the current article data to the backend.
"""
self.article_data = self.client._perform_json("PUT", "/projects/%s/wiki/%s" % (self.project_key, dku_quote_fn(self.article_id)), body=self.article_data)