datagrok-api 0.0.3__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
1
  Metadata-Version: 2.4
2
2
  Name: datagrok-api
3
- Version: 0.0.3
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,3 +1,4 @@
1
1
  from datagrok_api.datagrok_client import DatagrokClient
2
+ from datagrok_api.group import Group, GroupMembershipRequest, GroupRelation
2
3
 
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
@@ -0,0 +1,171 @@
1
+ from typing import Optional, List, TYPE_CHECKING
2
+ from datetime import datetime
3
+
4
+ from datagrok_api.model import Model
5
+
6
+ if TYPE_CHECKING:
7
+ from datagrok_client import DatagrokClient
8
+
9
+ from typing import Optional, List
10
+ from datetime import datetime
11
+
12
+ class Group(Model):
13
+ def __init__(self, client: Optional["DatagrokClient"] = None, **data):
14
+ super().__init__(data.get("id"))
15
+ self._client: "DatagrokClient" = client
16
+ self.name: Optional[str] = data.get("name")
17
+ self.friendly_name: Optional[str] = data.get("friendlyName")
18
+ self.description: Optional[str] = data.get("description")
19
+
20
+ created_str = data.get("createdOn")
21
+ self.created_on: Optional[datetime] = (
22
+ datetime.fromisoformat(created_str) if created_str else None
23
+ )
24
+
25
+ updated_str = data.get("updatedOn")
26
+ self.updated_on: Optional[datetime] = (
27
+ datetime.fromisoformat(updated_str) if updated_str else None
28
+ )
29
+
30
+ self.personal: bool = data.get("personal", False)
31
+ self.hidden: bool = data.get("hidden", False)
32
+
33
+ if data.get('parents') is None:
34
+ data["parents"] = []
35
+
36
+ if data.get('children') is None:
37
+ data["children"] = []
38
+
39
+ self.parents: List["GroupRelation"] = [
40
+ GroupRelation(client, **rel) for rel in data.get("parents")
41
+ ]
42
+
43
+ self.children: List["GroupRelation"] = [
44
+ GroupRelation(client, **rel) for rel in data.get("children")
45
+ ]
46
+
47
+ def _extract_groups(self, relations: List["GroupRelation"], admin: bool, direction: str) -> List["Group"]:
48
+ return [
49
+ getattr(rel, direction)
50
+ for rel in relations
51
+ if rel.is_admin == admin and getattr(rel, direction) is not None
52
+ ]
53
+
54
+ @property
55
+ def members(self) -> List["Group"]:
56
+ return self._extract_groups(self.children, admin=False, direction="child")
57
+
58
+ @property
59
+ def admin_members(self) -> List["Group"]:
60
+ return self._extract_groups(self.children, admin=True, direction="child")
61
+
62
+ @property
63
+ def memberships(self) -> List["Group"]:
64
+ return self._extract_groups(self.parents, admin=False, direction="parent")
65
+
66
+ @property
67
+ def admin_memberships(self) -> List["Group"]:
68
+ return self._extract_groups(self.parents, admin=True, direction="parent")
69
+
70
+ def request_membership(self) -> "GroupMembershipRequest":
71
+ return self._client.request_group_membership(self.id)
72
+
73
+ def get_membership_requests(self) -> List["GroupMembershipRequest"]:
74
+ return self._client.get_group_membership_requests(self.id)
75
+
76
+ def add_member(self, group: "Group", is_admin = False):
77
+ group.ensure_id()
78
+ existing = next((c for c in self.children if c.child and c.child.id == group.id), None)
79
+
80
+ if existing is not None:
81
+ existing.is_admin = is_admin
82
+ else:
83
+ rel = GroupRelation(self._client, isAdmin=is_admin)
84
+ rel.parent = Group(id=self.id)
85
+ rel.child = group
86
+ rel.ensure_id()
87
+ self.children.append(rel)
88
+
89
+ self._client.save_group(self, save_relations=True)
90
+
91
+ def to_dict(self):
92
+ return {
93
+ "id": self.id,
94
+ "name": self.name,
95
+ "friendlyName": self.friendly_name,
96
+ "description": self.description,
97
+ "createdOn": self.created_on.isoformat() if self.created_on else None,
98
+ "updatedOn": self.updated_on.isoformat() if self.updated_on else None,
99
+ "personal": self.personal,
100
+ "hidden": self.hidden,
101
+ "parents": [rel.to_dict() for rel in self.parents],
102
+ "children": [rel.to_dict() for rel in self.children],
103
+ }
104
+
105
+ class GroupRelation(Model):
106
+ def __init__(self, client: "DatagrokClient", **data):
107
+ super().__init__(data.get("id"))
108
+ self.is_admin: bool = data.get("isAdmin", False)
109
+
110
+ self.parent: Optional[Group] = (
111
+ Group(client, **data.get("parent")) if data.get("parent") else None
112
+ )
113
+ self.child: Optional[Group] = (
114
+ Group(client, **data.get("child")) if data.get("child") else None
115
+ )
116
+
117
+ def to_dict(self):
118
+ return {
119
+ "id": self.id,
120
+ "isAdmin": self.is_admin,
121
+ "parent": self.parent.to_dict() if self.parent else None,
122
+ "child": self.child.to_dict() if self.child else None,
123
+ }
124
+
125
+ class GroupMembershipRequest(Model):
126
+ def __init__(self, client: "DatagrokClient", **data):
127
+ super().__init__(data.get("id"))
128
+ self._client: "DatagrokClient" = client
129
+ self.approved: Optional[bool] = data.get("approved")
130
+ created_str = data.get("createdOn")
131
+ self.created_on: Optional[datetime] = (
132
+ datetime.fromisoformat(created_str) if created_str else None
133
+ )
134
+
135
+ updated_str = data.get("updatedOn")
136
+ self.updated_on: Optional[datetime] = (
137
+ datetime.fromisoformat(updated_str) if updated_str else None
138
+ )
139
+
140
+ resolution_str = data.get("resolutionDate")
141
+ self.resolution_date: Optional[datetime] = (
142
+ datetime.fromisoformat(resolution_str) if resolution_str else None
143
+ )
144
+
145
+ self.from_group: Optional[Group] = (
146
+ Group(client, **data.get("from")) if data.get("from") else None
147
+ )
148
+ self.to: Optional[Group] = (
149
+ Group(client, **data.get("to")) if data.get("to") else None
150
+ )
151
+
152
+ @property
153
+ def is_viewed(self) -> bool:
154
+ return self.approved is not None
155
+
156
+ def approve(self):
157
+ return self._client.approve_membership_request(self.id)
158
+
159
+ def deny(self):
160
+ return self._client.deny_membership_request(self.id)
161
+
162
+ def to_dict(self):
163
+ return {
164
+ "id": self.id,
165
+ "approved": self.approved,
166
+ "createdOn": self.created_on.isoformat() if self.created_on else None,
167
+ "updatedOn": self.updated_on.isoformat() if self.updated_on else None,
168
+ "resolutionDate": self.resolution_date.isoformat() if self.resolution_date else None,
169
+ "from": self.from_group.to_dict() if self.from_group else None,
170
+ "to": self.to.to_dict() if self.to else None,
171
+ }
@@ -0,0 +1,10 @@
1
+ import uuid
2
+
3
+ class Model:
4
+ def __init__(self, id):
5
+ self.id = id
6
+
7
+ def ensure_id(self) -> str:
8
+ if self.id is None:
9
+ self.id = str(uuid.uuid1())
10
+ return self.id