datagrok-api 0.0.2__tar.gz → 0.0.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # Virtual Environment
24
+ venv/
25
+ env/
26
+ ENV/
27
+ .env/
28
+ .venv/
29
+
30
+ # IDE
31
+ .idea/
32
+ .vscode/
33
+ *.swp
34
+ *.swo
35
+
36
+ # OS
37
+ .DS_Store
38
+ Thumbs.db
39
+
40
+ # Logs
41
+ *.log
42
+
43
+ # Coverage
44
+ .coverage
45
+ htmlcov/
46
+ .pytest_cache/
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: datagrok-api
3
- Version: 0.0.2
3
+ Version: 0.0.4
4
4
  Summary: Client library for integration with datagrok API
5
5
  Project-URL: Homepage, https://github.com/datagrok-ai/public
6
6
  Project-URL: Issues, https://github.com/datagrok-ai/public/issues
@@ -1,63 +1,63 @@
1
- # Datagrok python client library
2
-
3
- This library can be used for integration with datagrok. It is a python wrapper for public API, that has OpenAPI specification available [here](http://public.datagrok.ai/api/public/api.yaml).
4
-
5
- Refer to [Help](http://datagrok.ai/help) for more information.
6
-
7
- ## Installation
8
-
9
- To install package, use [pip](https://pypi.org/project/pip/).
10
-
11
- ```shell
12
- pip install datagrok-api
13
- ```
14
-
15
- ## Usage
16
-
17
- To use API client, import DatagrokClient to your project:
18
-
19
- ```python
20
- from datagrok_api import DatagrokClient
21
-
22
- api = DatagrokClient('your token', 'datagrok url')
23
- ```
24
-
25
- ## License
26
-
27
- See [License.md](https://github.com/datagrok-ai/public/blob/master/LICENSE.md).
28
-
29
- ## Examples
30
-
31
- The package uses Pandas for representation of tables and dataframes.
32
-
33
- ```python
34
- import pandas as pd
35
- from sklearn.datasets import load_iris
36
-
37
- # Calls a Datagrok function
38
- # Dataframes, columns and primitive data types are supported
39
- api.call_function('Abs', {
40
- 'x': -3
41
- })
42
-
43
- # Downloads file from a given connection
44
- res = api.download_file('system.demofiles', 'demog.csv')
45
- print(res.head())
46
-
47
- # Uploads iris dataset as a table
48
- iris_id = api.upload_table('iris', pd.DataFrame(load_iris()['data']))['ID']
49
-
50
- # Iris also can be uploaded as a file
51
- # api.upload_file('system.demofiles', 'iris.csv', 'iris.csv')
52
-
53
- # Fetches freshly uploaded Iris table
54
- res = api.download_table(iris_id)
55
- print(res.head())
56
-
57
- # Creates dashboard from iris table with layout uploaded from file "iris.layout"
58
- dashboard_id = api.create_dashboard('python-test', iris_id, layout_filename='iris.layout')['ID']
59
-
60
- # Shares dashboard with admin
61
- api.share_dashboard(dashboard_id, 'Test')
62
-
63
- ```
1
+ # Datagrok python client library
2
+
3
+ This library can be used for integration with datagrok. It is a python wrapper for public API, that has OpenAPI specification available [here](http://public.datagrok.ai/api/public/api.yaml).
4
+
5
+ Refer to [Help](http://datagrok.ai/help) for more information.
6
+
7
+ ## Installation
8
+
9
+ To install package, use [pip](https://pypi.org/project/pip/).
10
+
11
+ ```shell
12
+ pip install datagrok-api
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ To use API client, import DatagrokClient to your project:
18
+
19
+ ```python
20
+ from datagrok_api import DatagrokClient
21
+
22
+ api = DatagrokClient('your token', 'datagrok url')
23
+ ```
24
+
25
+ ## License
26
+
27
+ See [License.md](https://github.com/datagrok-ai/public/blob/master/LICENSE.md).
28
+
29
+ ## Examples
30
+
31
+ The package uses Pandas for representation of tables and dataframes.
32
+
33
+ ```python
34
+ import pandas as pd
35
+ from sklearn.datasets import load_iris
36
+
37
+ # Calls a Datagrok function
38
+ # Dataframes, columns and primitive data types are supported
39
+ api.call_function('Abs', {
40
+ 'x': -3
41
+ })
42
+
43
+ # Downloads file from a given connection
44
+ res = api.download_file('system.demofiles', 'demog.csv')
45
+ print(res.head())
46
+
47
+ # Uploads iris dataset as a table
48
+ iris_id = api.upload_table('iris', pd.DataFrame(load_iris()['data']))['ID']
49
+
50
+ # Iris also can be uploaded as a file
51
+ # api.upload_file('system.demofiles', 'iris.csv', 'iris.csv')
52
+
53
+ # Fetches freshly uploaded Iris table
54
+ res = api.download_table(iris_id)
55
+ print(res.head())
56
+
57
+ # Creates dashboard from iris table with layout uploaded from file "iris.layout"
58
+ dashboard_id = api.create_dashboard('python-test', iris_id, layout_filename='iris.layout')['ID']
59
+
60
+ # Shares dashboard with admin
61
+ api.share_dashboard(dashboard_id, 'Test')
62
+
63
+ ```
@@ -1,3 +1,4 @@
1
- from datagrok_api.datagrok_client import DatagrokClient
2
-
3
- '''Datagrok Public API Python wrapper'''
1
+ from datagrok_api.datagrok_client import DatagrokClient
2
+ from datagrok_api.group import Group, GroupMembershipRequest, GroupRelation
3
+
4
+ '''Datagrok Public API Python wrapper'''
@@ -0,0 +1,452 @@
1
+ from typing import List, Optional, Dict, Any, Union, BinaryIO
2
+ import requests
3
+ import pandas as pd
4
+ import json
5
+ from io import StringIO
6
+
7
+ from .group import Group, GroupMembershipRequest
8
+
9
+ class DatagrokClient:
10
+ def __init__(self, api_key: str, base_url: str) -> None:
11
+ '''
12
+ Create a datagrok api client.
13
+
14
+ Parameters
15
+ ----------
16
+ api_key: str
17
+ Api key for a client. Can be obtained from user profile page.
18
+ Starts with "Bearer".
19
+ base_url: str
20
+ Url of datagrok API. For example, "https://public.datagrok.ai/api"
21
+
22
+ Returns
23
+ -------
24
+ DatagrokClient
25
+ New instance of Datagrok Client
26
+ '''
27
+ self.api_key = api_key
28
+ self.base_url = base_url
29
+ self.headers = {
30
+ "Authorization": self.api_key
31
+ }
32
+
33
+ def download_table(self, name: str) -> pd.DataFrame:
34
+ '''
35
+ Downloads a table from Datagrok.
36
+
37
+ Parameters
38
+ ----------
39
+ name: str
40
+ Identifier of a table. Can be accessed from context panel.
41
+ Several options supppored: UUID, Grok names (e.g. Namespace.Project.Table)
42
+
43
+ Returns
44
+ -------
45
+ pandas.DataFrame
46
+ Dataframe with table data
47
+ '''
48
+ name = name.replace(':', '.')
49
+ endpoint = f"/public/v1/tables/{name}"
50
+ response = self._request('GET', endpoint, content_type="text/plain")
51
+ return pd.read_csv(StringIO(response.text))
52
+
53
+ def upload_table(self, name: str, dataframe: pd.DataFrame) -> Dict[str, Any]:
54
+ '''
55
+ Uploads a table to Datagrok.
56
+
57
+ Parameters
58
+ ----------
59
+ name: str
60
+ Name for new table.
61
+ If in grok format, can also specify project and namespace.
62
+ dataframe: pandas.Dataframe
63
+ table data to save
64
+
65
+ Returns
66
+ -------
67
+ Dict[str, Any]
68
+ set of identifiers for the uploaded table
69
+ '''
70
+ name = name.replace(':', '.')
71
+ endpoint = f"/public/v1/tables/{name}"
72
+ csv_data = dataframe.to_csv(index=False).encode("utf-8")
73
+ response = self._request('POST', endpoint, content_type="text/csv", data=csv_data)
74
+ return response.json()
75
+
76
+ def download_file(self, connector: str, path: str) -> Union[pd.DataFrame, bytes]:
77
+ '''
78
+ Download a file from Datagrok.
79
+
80
+ Parameters
81
+ ----------
82
+ connector: str
83
+ Identifier of a connector: ID or Grok name.
84
+ path: str
85
+ Path to file in a connector
86
+
87
+ Returns
88
+ -------
89
+ Union[pd.DataFrame, bytes]
90
+ If requested file is csv, returns corresponding pd.DataFrame.
91
+ Otherwise returns bytes with file content.
92
+ '''
93
+ connector = connector.replace(':', '.')
94
+ endpoint = f"/public/v1/files/{connector}/{path}"
95
+ response = self._request('GET', endpoint, content_type="application/octet-stream")
96
+ if path.endswith('.csv'):
97
+ return pd.read_csv(StringIO(response.content.decode('utf-8')))
98
+ return response.content
99
+
100
+ def upload_file(self, connector: str, path: str, file_path: str) -> None:
101
+ '''
102
+ Uploads a file to Datagrok.
103
+
104
+ Parameters
105
+ ----------
106
+ connector: str
107
+ Identifier of a connector: ID or Grok name.
108
+ path: str
109
+ Path to file in a connector
110
+ file_path: str
111
+ Path to local file that needs to be uploaded
112
+ '''
113
+ connector = connector.replace(':', '.')
114
+ endpoint = f"/public/v1/files/{connector}/{path}"
115
+ with open(file_path, 'rb') as file:
116
+ self._request('POST', endpoint, content_type="application/octet-stream", data=file)
117
+
118
+ def share_dashboard(self, id: str, groups: str, access: str = "View") -> None:
119
+ '''
120
+ Shares a dashboard.
121
+
122
+ Parameters
123
+ ----------
124
+ id: str
125
+ Identifier of a project: ID or Grok name.
126
+ groups: str
127
+ Comma-separated list of group/user names
128
+ access: str
129
+ Either 'View' or 'Edit'
130
+ '''
131
+ id = id.replace(':', '.')
132
+ endpoint = f"/public/v1/dashboards/{id}/shares"
133
+ params = {
134
+ 'groups': groups,
135
+ 'access': access
136
+ }
137
+ self._request('GET', endpoint, params=params)
138
+
139
+ def create_dashboard(self, name: str, table_ids: str, layout_filename: Optional[str] = None) -> Dict[str, Any]:
140
+ '''
141
+ Creates a dashboard.
142
+
143
+ Parameters
144
+ ----------
145
+ name: str
146
+ Name for new dashboard.
147
+ table_ids: str
148
+ Comma-separated list of table ids
149
+ layout_filename: Optional[str]
150
+ Optional. Filename for a project layout.
151
+
152
+ Returns
153
+ -------
154
+ Dict[str, Any]
155
+ Identifiers of a project.
156
+ '''
157
+ name = name.replace(':', '.')
158
+ table_ids = table_ids.replace(':', '.')
159
+ endpoint = f"/public/v1/dashboards/{name}/{table_ids}"
160
+ if layout_filename:
161
+ with open(layout_filename, 'r') as layout_file:
162
+ layout = json.load(layout_file)
163
+ response = self._request('POST', endpoint, json=layout, content_type="application/json")
164
+ else:
165
+ response = self._request('POST', endpoint, content_type="application/json")
166
+ return response.json()
167
+
168
+ def call_function(self, name: str, invocation_parameters: Dict[str, Any]) -> Any:
169
+ '''
170
+ Performs a call of datagrok function.
171
+
172
+ Parameters
173
+ ----------
174
+ name: str
175
+ Function name.
176
+ invocation_parameters: Dict[str, Any]
177
+ Dict with parameter values for function call.
178
+
179
+ Returns
180
+ -------
181
+ Any
182
+ Result of invocation: either a single value or a list or outputs.
183
+ '''
184
+ name = name.replace(':', '.')
185
+ endpoint = f"/public/v1/{name}/call"
186
+ response = self._request('POST', endpoint, json=invocation_parameters, content_type="application/json")
187
+ return response.json()
188
+
189
+ def list_groups(self, smart_filter: Optional[str] = None, include_personal: bool = False,
190
+ include_members: bool = False, include_memberships: bool = False) -> List[Group]:
191
+ '''
192
+ Lists user groups from Datagrok.
193
+
194
+ Parameters
195
+ ----------
196
+ smart_filter: Optional[str]
197
+ Optional. Smart search filter.
198
+ include_personal: bool
199
+ Optional. Include also personal groups.
200
+ include_members: bool
201
+ Optional. Include group members.
202
+ include_memberships: bool
203
+ Optional. Include group memberships.
204
+
205
+ Returns
206
+ -------
207
+ List[Group]
208
+ A list of Group instances.
209
+ '''
210
+ personal = str(include_personal).lower()
211
+ smart_filter = smart_filter or f"personal={personal}"
212
+ if smart_filter and not smart_filter.endswith(f"personal={personal}"):
213
+ smart_filter += f" and personal={personal}"
214
+
215
+ params = {"text": smart_filter}
216
+
217
+ include_parts = []
218
+ if include_members:
219
+ include_parts.append("children.child")
220
+ if include_memberships:
221
+ include_parts.append("parents.parent")
222
+
223
+ if include_parts:
224
+ params["include"] = ",".join(include_parts)
225
+
226
+ endpoint = "/public/v1/groups"
227
+ response = self._request('GET', endpoint, params=params)
228
+
229
+ return [Group(self, **group_data) for group_data in response.json()]
230
+
231
+ def lookup_groups(self, query: str) -> List[Group]:
232
+ '''
233
+ Looks up groups from Datagrok by name.
234
+
235
+ Parameters
236
+ ----------
237
+ query: str
238
+ Query string to match groups by name.
239
+
240
+ Returns
241
+ -------
242
+ List[Group]
243
+ A list of Group instances that match the query.
244
+ '''
245
+ params = {"query": query}
246
+ endpoint = "/public/v1/groups/lookup"
247
+ response = self._request('GET', endpoint, params=params)
248
+
249
+ return [Group(self, **group_data) for group_data in response.json()]
250
+
251
+ def get_group(self, group_id: str) -> Group:
252
+ '''
253
+ Retrieves the details of a specific group by its ID. Includes group members and memberships.
254
+
255
+ Parameters
256
+ ----------
257
+ group_id: str
258
+ The ID of the group to retrieve details for.
259
+
260
+ Returns
261
+ -------
262
+ Group
263
+ A Group instance containing the details of the group.
264
+ '''
265
+ endpoint = f"/public/v1/groups/{group_id}"
266
+ response = self._request('GET', endpoint)
267
+ return Group(self, **response.json())
268
+
269
+ def get_group_members(self, group_id: str, admin: Optional[bool] = None) -> List[Group]:
270
+ '''
271
+ Retrieves the members of a specific group by its ID.
272
+
273
+ Parameters
274
+ ----------
275
+ group_id: str
276
+ The ID of the group to retrieve members for.
277
+ admin: Optional[bool]
278
+ If set to True, only admin members will be included. If False, only non-admin members will be included.
279
+ If not provided, only non-admin members are included.
280
+
281
+ Returns
282
+ -------
283
+ List[Group]
284
+ A list of Group instances representing the members of the group.
285
+ '''
286
+ endpoint = f"/public/v1/groups/{group_id}/members"
287
+ params = {}
288
+ if admin is not None:
289
+ params["admin"] = admin
290
+ response = self._request('GET', endpoint, params=params)
291
+ return [Group(self, **group_data) for group_data in response.json()]
292
+
293
+ def get_group_memberships(self, group_id: str, admin: Optional[bool] = None) -> List[Group]:
294
+ '''
295
+ Retrieves the memberships of a specific group by its ID.
296
+
297
+ Parameters
298
+ ----------
299
+ group_id: str
300
+ The ID of the group to retrieve members for.
301
+ admin: Optional[bool]
302
+ If set to True, only admin memberships will be included. If False, only non-admin memberships will be included.
303
+ If not provided, only non-admin memberships are included.
304
+
305
+ Returns
306
+ -------
307
+ List[Group]
308
+ A list of Group instances representing the members of the group.
309
+ '''
310
+ endpoint = f"/public/v1/groups/{group_id}/memberships"
311
+ params = {}
312
+ if admin is not None:
313
+ params["admin"] = admin
314
+ response = self._request('GET', endpoint, params=params)
315
+ return [Group(self, **group_data) for group_data in response.json()]
316
+
317
+ def request_group_membership(self, group_id: str) -> GroupMembershipRequest:
318
+ '''
319
+ Submits a request to join a specific group by its ID.
320
+
321
+ Parameters
322
+ ----------
323
+ group_id: str
324
+ The ID of the group to request membership for.
325
+
326
+ Returns
327
+ -------
328
+ GroupMembershipRequest
329
+ The created membership request.
330
+ '''
331
+ endpoint = f"/public/v1/groups/{group_id}/request"
332
+ response = self._request('POST', endpoint)
333
+ return GroupMembershipRequest(self, **response.json())
334
+
335
+ def get_group_membership_requests(self, group_id: str) -> List[GroupMembershipRequest]:
336
+ '''
337
+ Retrieves a list of membership requests for a specific group.
338
+
339
+ Parameters
340
+ ----------
341
+ group_id: str
342
+ The ID of the group to retrieve membership requests for.
343
+
344
+ Returns
345
+ -------
346
+ List[GroupMembershipRequest]
347
+ A list of GroupMembershipRequest instances representing the requests for the group.
348
+ '''
349
+ endpoint = f"/public/v1/groups/{group_id}/requests"
350
+ response = self._request('GET', endpoint)
351
+ return [GroupMembershipRequest(self, **request_data) for request_data in response.json()]
352
+
353
+ def approve_membership_request(self, request_id: str) -> None:
354
+ """
355
+ Approve a membership request for a group.
356
+
357
+ Parameters
358
+ ----------
359
+ request_id: str
360
+ The ID of the membership request to approve.
361
+
362
+ Returns
363
+ -------
364
+ None
365
+ This method performs an approval action and does not return anything.
366
+ """
367
+ endpoint = f"/public/v1/groups/requests/{request_id}/approve"
368
+ self._request('POST', endpoint)
369
+
370
+ def deny_membership_request(self, request_id: str) -> None:
371
+ """
372
+ Deny a membership request for a group.
373
+
374
+ Parameters
375
+ ----------
376
+ request_id: str
377
+ The ID of the membership request to deny.
378
+
379
+ Returns
380
+ -------
381
+ None
382
+ This method performs a denial action and does not return anything.
383
+ """
384
+ endpoint = f"/public/v1/groups/requests/{request_id}/deny"
385
+ self._request('POST', endpoint)
386
+
387
+ def get_current_user_group(self) -> Group:
388
+ """
389
+ Get the current user's group. Includes members and memberships
390
+
391
+ Returns
392
+ -------
393
+ Group
394
+ The current user's group instance.
395
+ """
396
+ endpoint = "/public/v1/user/group"
397
+ response = self._request('GET', endpoint)
398
+ return Group(self, **response.json())
399
+
400
+ def save_group(self, group: Group, save_relations: bool = False) -> Group:
401
+ """
402
+ Saves or updates group.
403
+
404
+ Parameters
405
+ ----------
406
+ group: Group
407
+ The group to save or update.
408
+ save_relations: bool
409
+ Whether to save group relations (members and memberships).
410
+
411
+ Returns
412
+ -------
413
+ Group
414
+ The saved group instance.
415
+ """
416
+ group.ensure_id()
417
+ endpoint = "/public/v1/groups"
418
+ response = self._request('POST', endpoint, json=group.to_dict(), params={'saveRelations': str(save_relations).lower()})
419
+ return Group(self, **response.json())
420
+
421
+ def _request(self, method: str, endpoint: str, content_type: str = "application/json", **kwargs: Any) -> requests.Response:
422
+ """
423
+ Internal method to make HTTP requests to the Datagrok API.
424
+
425
+ Parameters
426
+ ----------
427
+ method: str
428
+ HTTP method to use (GET, POST, etc.)
429
+ endpoint: str
430
+ API endpoint to call
431
+ content_type: str
432
+ Content type for the request
433
+ **kwargs: Any
434
+ Additional arguments to pass to requests.request
435
+
436
+ Returns
437
+ -------
438
+ requests.Response
439
+ The response from the API
440
+ """
441
+ url = f"{self.base_url}{endpoint}"
442
+ headers = self.headers.copy()
443
+ headers["Content-Type"] = content_type
444
+ response = requests.request(method, url, headers=headers, **kwargs)
445
+ response.raise_for_status()
446
+ if 'api-error' in response.headers:
447
+ content = response.content.decode()
448
+ if 'ApiError' in content:
449
+ raise Exception(content)
450
+ else:
451
+ raise Exception("Something went wrong during request")
452
+ return response