datagrok-api 0.0.9__tar.gz → 0.1.0__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.
Files changed (29) hide show
  1. datagrok_api-0.1.0/PKG-INFO +104 -0
  2. datagrok_api-0.1.0/README.md +83 -0
  3. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/datagrok_client.py +11 -0
  4. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/models/__init__.py +4 -2
  5. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/models/data_connection.py +18 -7
  6. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/models/func.py +13 -1
  7. datagrok_api-0.1.0/datagrok_api/models/package.py +146 -0
  8. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/models/script.py +7 -2
  9. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/resources/__init__.py +4 -1
  10. datagrok_api-0.1.0/datagrok_api/resources/credentials.py +77 -0
  11. datagrok_api-0.1.0/datagrok_api/resources/packages.py +71 -0
  12. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/pyproject.toml +1 -2
  13. datagrok_api-0.0.9/PKG-INFO +0 -171
  14. datagrok_api-0.0.9/README.md +0 -149
  15. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/.gitignore +0 -0
  16. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/__init__.py +0 -0
  17. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/http_client.py +0 -0
  18. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/models/group.py +0 -0
  19. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/models/model.py +0 -0
  20. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/models/query.py +0 -0
  21. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/models/share_response.py +0 -0
  22. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/models/user.py +0 -0
  23. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/resources/connections.py +0 -0
  24. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/resources/files.py +0 -0
  25. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/resources/functions.py +0 -0
  26. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/resources/groups.py +0 -0
  27. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/resources/shares.py +0 -0
  28. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/resources/tables.py +0 -0
  29. {datagrok_api-0.0.9 → datagrok_api-0.1.0}/datagrok_api/resources/users.py +0 -0
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: datagrok-api
3
+ Version: 0.1.0
4
+ Summary: Client library for integration with datagrok API
5
+ Project-URL: Homepage, https://github.com/datagrok-ai/public
6
+ Project-URL: Issues, https://github.com/datagrok-ai/public/issues
7
+ Author-email: Andrew Skalkin <askalkin@datagrok.ai>, Amelichev Konstantin <kamelichev@datagrok.ai>
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Requires-Dist: pandas
13
+ Requires-Dist: requests
14
+ Requires-Dist: requests-toolbelt
15
+ Provides-Extra: test
16
+ Requires-Dist: data-to-xml; extra == 'test'
17
+ Requires-Dist: pytest; extra == 'test'
18
+ Requires-Dist: pytest-item-dict; extra == 'test'
19
+ Requires-Dist: pytest-xml; extra == 'test'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # Datagrok python client library
23
+
24
+ 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).
25
+
26
+ Refer to [Help](http://datagrok.ai/help) for more information.
27
+
28
+ ## Installation
29
+
30
+ To install package, use [pip](https://pypi.org/project/pip/).
31
+
32
+ ```shell
33
+ pip install datagrok-api
34
+ ```
35
+
36
+ ## Usage
37
+
38
+ ### Initialization
39
+ To use the API client, import `DatagrokClient`. It is recommended to use it as a context manager to ensure proper connection handling:
40
+
41
+ ```python
42
+ from datagrok_api import DatagrokClient
43
+
44
+ # Initialize with your server URL and API token
45
+ with DatagrokClient("https://public.datagrok.ai/api", "Bearer <your-token>") as grok:
46
+ me = grok.users.current()
47
+ print(f"Logged in as: {me.first_name} {me.last_name}")
48
+ ```
49
+
50
+ ### Working with Data (Tables & Files)
51
+ The package uses Pandas for representation of tables and dataframes.
52
+
53
+ ```python
54
+ import pandas as pd
55
+ from sklearn.datasets import load_iris
56
+
57
+ # Upload a DataFrame as a table
58
+ iris_df = pd.DataFrame(load_iris()['data'])
59
+ iris_id = grok.tables.upload('iris', iris_df)['ID']
60
+
61
+ # Download a table by ID or Name
62
+ df = grok.tables.download(iris_id)
63
+ print(df.head())
64
+
65
+ # Upload a local file
66
+ uploaded_file = grok.files.upload("data.csv")
67
+ ```
68
+
69
+ ### Functions & Connections
70
+ You can call server-side functions and manage data connections directly through their respective managers.
71
+
72
+ ```python
73
+ from datagrok_api.models import DataConnection, FileDataSourceType, Credentials
74
+
75
+ # Call a Datagrok function
76
+ result = grok.functions.call("JohnDoe:MyFunction", {"a": 1, "b": 2})
77
+
78
+ # Create and save a connection (e.g., S3)
79
+ creds = Credentials(accessKey="aws-key", secretKey="aws-secret")
80
+ conn = DataConnection(
81
+ name="My S3 Bucket",
82
+ data_source=FileDataSourceType.S3,
83
+ bucket="my-bucket",
84
+ region="us-east-1",
85
+ credentials=creds
86
+ )
87
+ saved_conn = grok.connections.save(conn)
88
+ ```
89
+
90
+ ### Group Management
91
+ Manage user groups and metadata.
92
+
93
+ ```python
94
+ # Search for a group and update its properties
95
+ groups = grok.groups.find("Chemists")
96
+ if groups:
97
+ group = groups[0]
98
+ group.description = "Updated description for the team"
99
+ grok.groups.save(group)
100
+ ```
101
+
102
+ ## License
103
+
104
+ See [License](https://github.com/datagrok-ai/public/blob/master/LICENSE.md).
@@ -0,0 +1,83 @@
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
+ ### Initialization
18
+ To use the API client, import `DatagrokClient`. It is recommended to use it as a context manager to ensure proper connection handling:
19
+
20
+ ```python
21
+ from datagrok_api import DatagrokClient
22
+
23
+ # Initialize with your server URL and API token
24
+ with DatagrokClient("https://public.datagrok.ai/api", "Bearer <your-token>") as grok:
25
+ me = grok.users.current()
26
+ print(f"Logged in as: {me.first_name} {me.last_name}")
27
+ ```
28
+
29
+ ### Working with Data (Tables & Files)
30
+ The package uses Pandas for representation of tables and dataframes.
31
+
32
+ ```python
33
+ import pandas as pd
34
+ from sklearn.datasets import load_iris
35
+
36
+ # Upload a DataFrame as a table
37
+ iris_df = pd.DataFrame(load_iris()['data'])
38
+ iris_id = grok.tables.upload('iris', iris_df)['ID']
39
+
40
+ # Download a table by ID or Name
41
+ df = grok.tables.download(iris_id)
42
+ print(df.head())
43
+
44
+ # Upload a local file
45
+ uploaded_file = grok.files.upload("data.csv")
46
+ ```
47
+
48
+ ### Functions & Connections
49
+ You can call server-side functions and manage data connections directly through their respective managers.
50
+
51
+ ```python
52
+ from datagrok_api.models import DataConnection, FileDataSourceType, Credentials
53
+
54
+ # Call a Datagrok function
55
+ result = grok.functions.call("JohnDoe:MyFunction", {"a": 1, "b": 2})
56
+
57
+ # Create and save a connection (e.g., S3)
58
+ creds = Credentials(accessKey="aws-key", secretKey="aws-secret")
59
+ conn = DataConnection(
60
+ name="My S3 Bucket",
61
+ data_source=FileDataSourceType.S3,
62
+ bucket="my-bucket",
63
+ region="us-east-1",
64
+ credentials=creds
65
+ )
66
+ saved_conn = grok.connections.save(conn)
67
+ ```
68
+
69
+ ### Group Management
70
+ Manage user groups and metadata.
71
+
72
+ ```python
73
+ # Search for a group and update its properties
74
+ groups = grok.groups.find("Chemists")
75
+ if groups:
76
+ group = groups[0]
77
+ group.description = "Updated description for the team"
78
+ grok.groups.save(group)
79
+ ```
80
+
81
+ ## License
82
+
83
+ See [License](https://github.com/datagrok-ai/public/blob/master/LICENSE.md).
@@ -1,8 +1,10 @@
1
1
  from datagrok_api.http_client import HttpClient
2
2
  from datagrok_api.resources.connections import ConnectionsClient
3
+ from datagrok_api.resources.credentials import CredentialsClient
3
4
  from datagrok_api.resources.files import FilesClient
4
5
  from datagrok_api.resources.functions import FunctionsClient
5
6
  from datagrok_api.resources.groups import GroupsClient
7
+ from datagrok_api.resources.packages import PackagesClient, PublishedPackagesClient
6
8
  from datagrok_api.resources.shares import SharesClient
7
9
  from datagrok_api.resources.tables import TablesClient
8
10
  from datagrok_api.resources.users import UsersClient
@@ -40,6 +42,12 @@ class DatagrokClient:
40
42
  Provides information about platform users.
41
43
  connections : ConnectionsClient
42
44
  Interact with DataConnections (e.g., Postgres, Snowflake, S3, etc.).
45
+ packages : PackagesClient
46
+ List and retrieve Datagrok packages.
47
+ published_packages : PublishedPackagesClient
48
+ List and retrieve published package versions.
49
+ credentials : CredentialsClient
50
+ Manage credentials for any entity (connections, packages, etc.).
43
51
 
44
52
  Examples
45
53
  --------
@@ -95,6 +103,9 @@ class DatagrokClient:
95
103
  self.shares = SharesClient(client=self._http)
96
104
  self.users = UsersClient(client=self._http)
97
105
  self.connections = ConnectionsClient(client=self._http)
106
+ self.packages = PackagesClient(client=self._http)
107
+ self.published_packages = PublishedPackagesClient(client=self._http)
108
+ self.credentials = CredentialsClient(client=self._http)
98
109
 
99
110
 
100
111
  def close(self):
@@ -5,10 +5,12 @@ from .script import Script, ScriptLanguage
5
5
  from .func import Func, FuncParam, PropertyType
6
6
  from .model import Model
7
7
  from .data_connection import DataConnection, Credentials, DatabaseDataSourceType, FileDataSourceType, DataSourceType
8
+ from .package import Package, PublishedPackage
8
9
  from .share_response import ShareResponse
9
10
 
10
11
  __all__ = [
11
12
  "User", "Group", "DataQuery", "Script", "ScriptLanguage",
12
- "Func", "FuncParam", "PropertyType", "Model", "DataConnection", "ShareResponse",
13
- "DatabaseDataSourceType", "Credentials", "FileDataSourceType", "DataSourceType"
13
+ "Func", "FuncParam", "PropertyType", "Model", "DataConnection", "ShareResponse",
14
+ "DatabaseDataSourceType", "Credentials", "FileDataSourceType", "DataSourceType",
15
+ "Package", "PublishedPackage"
14
16
  ]
@@ -2,6 +2,7 @@ from enum import Enum
2
2
  from typing import List, Optional, Union
3
3
  from datetime import datetime
4
4
  from datagrok_api.models.model import Model, NamedModel
5
+ from datagrok_api.models.group import Group
5
6
 
6
7
 
7
8
  class DataSourceType(str, Enum):
@@ -112,28 +113,38 @@ class Credentials(Model):
112
113
  >>> print(aws_creds.access_key) # Access AWS access key
113
114
  >>> aws_creds.secret_key = "NEW_SECRET" # Update secret key dynamically
114
115
  """
115
- _explicit_attrs = {"id", "parameters", "open_parameters"}
116
- def __init__(self, **kwargs):
116
+ _explicit_attrs = {"id", "parameters", "open_parameters", "entity_bind_id", "group"}
117
+ def __init__(self, entity_bind_id: Optional[str] = None, group: Optional['Group'] = None, **kwargs):
117
118
  super().__init__(None)
118
119
  self.parameters = dict(kwargs)
119
120
  self.open_parameters = dict()
121
+ self.entity_bind_id = entity_bind_id
122
+ self.group = group
120
123
 
121
124
  def get(self, key, default=None):
122
125
  return self.parameters.get(key, default)
123
126
 
124
127
  def to_dict(self):
125
- return {
128
+ d = {
126
129
  "id": self.id,
127
130
  "parameters": self.parameters,
128
- "openParameters": self.open_parameters
129
- }
131
+ "openParameters": self.open_parameters,
132
+ "entityBindId": self.entity_bind_id,
133
+ }
134
+ if self.group is not None:
135
+ d["group"] = self.group.to_dict()
136
+ return d
130
137
 
131
138
  @classmethod
132
139
  def from_dict(cls, data: dict) -> 'Credentials':
133
- creds = cls(**data.get('parameters', {}))
140
+ group_data = data.get('group')
141
+ group = Group.from_dict(group_data) if group_data else None
142
+ creds = cls(entity_bind_id=data.get('entityBindId'),
143
+ group=group,
144
+ **data.get('parameters', {}))
134
145
  creds.id = data.get('id')
135
146
  creds.open_parameters = data.get('openParameters', {})
136
- return creds
147
+ return creds
137
148
 
138
149
  def __getattr__(self, name):
139
150
  if name in self.parameters:
@@ -33,7 +33,12 @@ class FuncParam:
33
33
 
34
34
  @classmethod
35
35
  def from_dict(cls, data: dict) -> 'FuncParam':
36
- return cls(name=data.get("name"), type=PropertyType(data.get("propertyType")), is_input=data.get("isInput", True))
36
+ prop_type = data.get("propertyType")
37
+ try:
38
+ prop_type = PropertyType(prop_type)
39
+ except ValueError:
40
+ pass
41
+ return cls(name=data.get("name"), type=prop_type, is_input=data.get("isInput", True))
37
42
 
38
43
  class Func(NamedModel):
39
44
  """
@@ -137,9 +142,16 @@ class Func(NamedModel):
137
142
  return subclass
138
143
  return decorator
139
144
 
145
+ _type_to_source = {
146
+ "Script": "script",
147
+ "DataQuery": "data-query",
148
+ }
149
+
140
150
  @classmethod
141
151
  def from_dict(cls, data: dict) -> "Func":
142
152
  source = data.get("source")
153
+ if source is None:
154
+ source = Func._type_to_source.get(data.get("#type"))
143
155
  subclass = Func._registry.get(source, cls)
144
156
  return subclass._from_dict(data)
145
157
 
@@ -0,0 +1,146 @@
1
+ from typing import Optional
2
+ from datetime import datetime
3
+ from datagrok_api.models.model import NamedModel
4
+
5
+
6
+ class Package(NamedModel):
7
+ """
8
+ Represents a Datagrok package (plugin).
9
+
10
+ Attributes
11
+ ----------
12
+ full_name : Optional[str]
13
+ Full package name (e.g., npm scope name).
14
+ description : Optional[str]
15
+ Package description.
16
+ category : Optional[str]
17
+ Package category.
18
+ image_url : Optional[str]
19
+ URL of the package icon/image.
20
+ url : Optional[str]
21
+ Package repository or homepage URL.
22
+ """
23
+ def __init__(self,
24
+ name: str,
25
+ id: Optional[str] = None,
26
+ friendly_name: Optional[str] = None,
27
+ full_name: Optional[str] = None,
28
+ description: Optional[str] = None,
29
+ category: Optional[str] = None,
30
+ image_url: Optional[str] = None,
31
+ url: Optional[str] = None,
32
+ created_on: Optional[datetime] = None,
33
+ updated_on: Optional[datetime] = None):
34
+ super().__init__(id=id, name=name, friendly_name=friendly_name,
35
+ created_on=created_on, updated_on=updated_on)
36
+ self.full_name = full_name
37
+ self.description = description
38
+ self.category = category
39
+ self.image_url = image_url
40
+ self.url = url
41
+
42
+ def to_dict(self):
43
+ return {
44
+ "id": self.id,
45
+ "name": self.name,
46
+ "friendlyName": self.friendly_name,
47
+ "fullName": self.full_name,
48
+ "description": self.description,
49
+ "category": self.category,
50
+ "imageUrl": self.image_url,
51
+ "url": self.url,
52
+ "createdOn": self.created_on.isoformat() if self.created_on else None,
53
+ "updatedOn": self.updated_on.isoformat() if self.updated_on else None,
54
+ }
55
+
56
+ @classmethod
57
+ def from_dict(cls, data: dict) -> 'Package':
58
+ pkg = cls(
59
+ name=data.get("name", ""),
60
+ id=data.get("id"),
61
+ friendly_name=data.get("friendlyName"),
62
+ full_name=data.get("fullName"),
63
+ description=data.get("description"),
64
+ category=data.get("category"),
65
+ image_url=data.get("imageUrl"),
66
+ url=data.get("url"),
67
+ )
68
+ created_str = data.get("createdOn")
69
+ pkg.created_on = datetime.fromisoformat(created_str) if created_str else None
70
+ updated_str = data.get("updatedOn")
71
+ pkg.updated_on = datetime.fromisoformat(updated_str) if updated_str else None
72
+ return pkg
73
+
74
+
75
+ class PublishedPackage(NamedModel):
76
+ """
77
+ Represents a published version of a Datagrok package.
78
+
79
+ Attributes
80
+ ----------
81
+ version : Optional[str]
82
+ Version string (e.g., "1.2.3").
83
+ is_current : bool
84
+ Whether this is the currently active version.
85
+ debug : bool
86
+ Whether this is a debug (dev) build.
87
+ package_author : Optional[str]
88
+ Author of the package.
89
+ published_on : Optional[datetime]
90
+ When this version was published.
91
+ commit : Optional[str]
92
+ Git commit hash.
93
+ """
94
+ def __init__(self,
95
+ name: str,
96
+ id: Optional[str] = None,
97
+ friendly_name: Optional[str] = None,
98
+ version: Optional[str] = None,
99
+ is_current: bool = False,
100
+ debug: bool = False,
101
+ package_author: Optional[str] = None,
102
+ published_on: Optional[datetime] = None,
103
+ commit: Optional[str] = None,
104
+ created_on: Optional[datetime] = None,
105
+ updated_on: Optional[datetime] = None):
106
+ super().__init__(id=id, name=name, friendly_name=friendly_name,
107
+ created_on=created_on, updated_on=updated_on)
108
+ self.version = version
109
+ self.is_current = is_current
110
+ self.debug = debug
111
+ self.package_author = package_author
112
+ self.published_on = published_on
113
+ self.commit = commit
114
+
115
+ def to_dict(self):
116
+ return {
117
+ "id": self.id,
118
+ "name": self.name,
119
+ "friendlyName": self.friendly_name,
120
+ "version": self.version,
121
+ "isCurrent": self.is_current,
122
+ "debug": self.debug,
123
+ "packageAuthor": self.package_author,
124
+ "publishedOn": self.published_on.isoformat() if self.published_on else None,
125
+ "commit": self.commit,
126
+ "createdOn": self.created_on.isoformat() if self.created_on else None,
127
+ "updatedOn": self.updated_on.isoformat() if self.updated_on else None,
128
+ }
129
+
130
+ @classmethod
131
+ def from_dict(cls, data: dict) -> 'PublishedPackage':
132
+ pkg = cls(
133
+ name=data.get("name", ""),
134
+ id=data.get("id"),
135
+ friendly_name=data.get("friendlyName"),
136
+ version=data.get("version"),
137
+ is_current=data.get("isCurrent", False),
138
+ debug=data.get("debug", False),
139
+ package_author=data.get("packageAuthor"),
140
+ commit=data.get("commit"),
141
+ )
142
+ for field, key in [("created_on", "createdOn"), ("updated_on", "updatedOn"), ("published_on", "publishedOn")]:
143
+ val = data.get(key)
144
+ if val:
145
+ setattr(pkg, field, datetime.fromisoformat(val))
146
+ return pkg
@@ -112,14 +112,19 @@ class Script(Func):
112
112
  def to_dict(self):
113
113
  d = super().to_dict()
114
114
  d["script"] = self.script
115
- d["language"] = self.language.value
115
+ d["language"] = self.language.value if isinstance(self.language, ScriptLanguage) else self.language
116
116
  return d
117
117
 
118
118
  @classmethod
119
119
  def _from_dict(cls, data: dict) -> "Script":
120
+ lang = data.get("language")
121
+ try:
122
+ lang = ScriptLanguage(lang) if lang else None
123
+ except ValueError:
124
+ pass
120
125
  return cls(
121
126
  script=data.get("script"),
122
- language=ScriptLanguage(data.get("language")),
127
+ language=lang,
123
128
  id=data.get("id"),
124
129
  name=data.get("name"),
125
130
  friendly_name=data.get("friendlyName"),
@@ -4,9 +4,12 @@ from .functions import FunctionsClient
4
4
  from .tables import TablesClient
5
5
  from .shares import SharesClient
6
6
  from .connections import ConnectionsClient
7
+ from .credentials import CredentialsClient
7
8
  from .files import FilesClient
9
+ from .packages import PackagesClient, PublishedPackagesClient
8
10
 
9
11
  __all__ = [
10
12
  "UsersClient", "GroupsClient", "FunctionsClient",
11
- "TablesClient", "SharesClient", "FilesClient", "ConnectionsClient"
13
+ "TablesClient", "SharesClient", "FilesClient", "ConnectionsClient",
14
+ "CredentialsClient", "PackagesClient", "PublishedPackagesClient"
12
15
  ]
@@ -0,0 +1,77 @@
1
+ from typing import Union
2
+ from urllib.parse import quote
3
+ from datagrok_api.http_client import HttpClient
4
+ from datagrok_api.models.data_connection import Credentials
5
+
6
+
7
+ class CredentialsClient:
8
+ """
9
+ Client for managing credentials for any Datagrok entity.
10
+
11
+ Credentials can be associated with data connections, packages,
12
+ or other entity types.
13
+
14
+ Parameters
15
+ ----------
16
+ client : HttpClient
17
+ An initialized HTTP client used for making API requests.
18
+
19
+ Examples
20
+ --------
21
+ Get credentials for a connection
22
+
23
+ >>> creds = grok.credentials.for_entity(connection.id)
24
+ >>> print(creds.parameters)
25
+
26
+ Save credentials for a package
27
+
28
+ >>> creds = grok.credentials.for_entity(package.id)
29
+ >>> creds.parameters['apiKey'] = 'new-key'
30
+ >>> grok.credentials.save(creds)
31
+ """
32
+ def __init__(self, client: HttpClient):
33
+ self.client = client
34
+
35
+ def for_entity(self, entity_id: str) -> Credentials:
36
+ """Get credentials for an entity by its ID.
37
+
38
+ Parameters
39
+ ----------
40
+ entity_id : str
41
+ The entity ID (UUID) to retrieve credentials for.
42
+
43
+ Returns
44
+ -------
45
+ Credentials
46
+ The credentials associated with the entity.
47
+ """
48
+ endpoint = f"/public/v1/credentials/for/{quote(entity_id)}"
49
+ response = self.client.get(endpoint)
50
+ return Credentials.from_dict(response.json())
51
+
52
+ def save(self, credentials: Credentials) -> None:
53
+ """Save or update credentials.
54
+
55
+ The credentials must have ``entity_bind_id`` set to associate
56
+ them with an entity. Typically, first call ``for_entity()`` to
57
+ load existing credentials, modify parameters, then save.
58
+
59
+ Parameters
60
+ ----------
61
+ credentials : Credentials
62
+ The credentials object to save.
63
+ """
64
+ endpoint = "/public/v1/credentials"
65
+ self.client.post(endpoint, json=credentials.to_dict())
66
+
67
+ def delete(self, credentials: Union[Credentials, str]) -> None:
68
+ """Delete credentials by object or ID.
69
+
70
+ Parameters
71
+ ----------
72
+ credentials : Credentials or str
73
+ The credentials object or credentials ID to delete.
74
+ """
75
+ cred_id = credentials.id if isinstance(credentials, Credentials) else credentials
76
+ endpoint = f"/public/v1/credentials/{quote(cred_id)}"
77
+ self.client.delete(endpoint)
@@ -0,0 +1,71 @@
1
+ from typing import List, Optional
2
+ from urllib.parse import quote
3
+ from datagrok_api.http_client import HttpClient
4
+ from datagrok_api.models.package import Package, PublishedPackage
5
+
6
+
7
+ class PackagesClient:
8
+ """
9
+ Client for listing and retrieving Datagrok packages.
10
+
11
+ Examples
12
+ --------
13
+ >>> packages = grok.packages.list()
14
+ >>> pkg = grok.packages.get("Chem")
15
+ """
16
+ def __init__(self, client: HttpClient):
17
+ self.client = client
18
+
19
+ def get(self, package: str) -> Package:
20
+ """Get a package by ID or name."""
21
+ endpoint = f"/public/v1/packages/{quote(package)}"
22
+ response = self.client.get(endpoint)
23
+ return Package.from_dict(response.json())
24
+
25
+ def list(self, smart_filter: Optional[str] = None) -> List[Package]:
26
+ """List packages with optional text filter."""
27
+ params = {}
28
+ if smart_filter:
29
+ params["text"] = smart_filter
30
+ endpoint = "/public/v1/packages"
31
+ response = self.client.get(endpoint, params=params)
32
+ return [Package.from_dict(data) for data in response.json()]
33
+
34
+
35
+ class PublishedPackagesClient:
36
+ """
37
+ Client for listing and retrieving published package versions.
38
+
39
+ Examples
40
+ --------
41
+ >>> published = grok.published_packages.list()
42
+ >>> pkg = grok.published_packages.get(published[0].id)
43
+ """
44
+ def __init__(self, client: HttpClient):
45
+ self.client = client
46
+
47
+ def get(self, id: str) -> PublishedPackage:
48
+ """Get a published package version by ID."""
49
+ endpoint = f"/public/v1/packages/published/{quote(id)}"
50
+ response = self.client.get(endpoint)
51
+ return PublishedPackage.from_dict(response.json())
52
+
53
+ def list(self, smart_filter: Optional[str] = None,
54
+ package_id: Optional[str] = None) -> List[PublishedPackage]:
55
+ """List published package versions.
56
+
57
+ Parameters
58
+ ----------
59
+ smart_filter : str, optional
60
+ Text filter to search published packages.
61
+ package_id : str, optional
62
+ Filter by parent package ID.
63
+ """
64
+ params = {}
65
+ if smart_filter:
66
+ params["text"] = smart_filter
67
+ if package_id:
68
+ params["packageId"] = package_id
69
+ endpoint = "/public/v1/packages/published"
70
+ response = self.client.get(endpoint, params=params)
71
+ return [PublishedPackage.from_dict(data) for data in response.json()]
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "datagrok-api"
7
- version = "0.0.9"
7
+ version = "0.1.0"
8
8
  authors = [
9
9
  { name="Andrew Skalkin", email="askalkin@datagrok.ai" },
10
10
  { name="Amelichev Konstantin", email="kamelichev@datagrok.ai" },
@@ -44,7 +44,6 @@ test = [
44
44
  "pytest-xml",
45
45
  "pytest-item-dict",
46
46
  "data_to_xml",
47
- "requests-mock"
48
47
  ]
49
48
 
50
49
  [project.urls]
@@ -1,171 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: datagrok-api
3
- Version: 0.0.9
4
- Summary: Client library for integration with datagrok API
5
- Project-URL: Homepage, https://github.com/datagrok-ai/public
6
- Project-URL: Issues, https://github.com/datagrok-ai/public/issues
7
- Author-email: Andrew Skalkin <askalkin@datagrok.ai>, Amelichev Konstantin <kamelichev@datagrok.ai>
8
- Classifier: License :: OSI Approved :: MIT License
9
- Classifier: Operating System :: OS Independent
10
- Classifier: Programming Language :: Python :: 3
11
- Requires-Python: >=3.8
12
- Requires-Dist: pandas
13
- Requires-Dist: requests
14
- Requires-Dist: requests-toolbelt
15
- Provides-Extra: test
16
- Requires-Dist: data-to-xml; extra == 'test'
17
- Requires-Dist: pytest; extra == 'test'
18
- Requires-Dist: pytest-item-dict; extra == 'test'
19
- Requires-Dist: pytest-xml; extra == 'test'
20
- Requires-Dist: requests-mock; extra == 'test'
21
- Description-Content-Type: text/markdown
22
-
23
- # Datagrok python client library
24
-
25
- 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).
26
-
27
- Refer to [Help](http://datagrok.ai/help) for more information.
28
-
29
- ## Installation
30
-
31
- To install package, use [pip](https://pypi.org/project/pip/).
32
-
33
- ```shell
34
- pip install datagrok-api
35
- ```
36
-
37
- ## Usage
38
-
39
- To use API client, import DatagrokClient to your project:
40
-
41
- ```python
42
- from datagrok_api import DatagrokClient
43
-
44
- api = DatagrokClient('your token', 'datagrok url')
45
- ```
46
-
47
- ## License
48
-
49
- See [License.md](https://github.com/datagrok-ai/public/blob/master/LICENSE.md).
50
-
51
- ## Examples
52
-
53
- The package uses Pandas for representation of tables and dataframes.
54
-
55
- ```python
56
- import pandas as pd
57
- from sklearn.datasets import load_iris
58
-
59
- # Calls a Datagrok function
60
- # Dataframes, columns and primitive data types are supported
61
- api.call_function('Abs', {
62
- 'x': -3
63
- })
64
-
65
- # Downloads file from a given connection
66
- res = api.download_file('system.demofiles', 'demog.csv')
67
- print(res.head())
68
-
69
- # Uploads iris dataset as a table
70
- iris_id = api.upload_table('iris', pd.DataFrame(load_iris()['data']))['ID']
71
-
72
- # Iris also can be uploaded as a file
73
- # api.upload_file('system.demofiles', 'iris.csv', 'iris.csv')
74
-
75
- # Fetches freshly uploaded Iris table
76
- res = api.download_table(iris_id)
77
- print(res.head())
78
-
79
- # Creates dashboard from iris table with layout uploaded from file "iris.layout"
80
- dashboard_id = api.create_dashboard('python-test', iris_id, layout_filename='iris.layout')['ID']
81
-
82
- # Shares dashboard with admin
83
- api.share_dashboard(dashboard_id, 'Test')
84
-
85
- # Group Management Examples
86
-
87
- # List all groups (excluding personal groups)
88
- groups = api.list_groups(include_personal=False)
89
- print("All groups:", [group.friendly_name for group in groups])
90
-
91
- # List groups with members and memberships
92
- groups_with_details = api.list_groups(
93
- include_personal=False,
94
- include_members=True,
95
- include_memberships=True
96
- )
97
- for group in groups_with_details:
98
- print(f"Group: {group.friendly_name}")
99
- print(f"Members: {[m.friendly_name for m in group.members]}")
100
- print(f"Memberships: {[m.friendly_name for m in group.memberships]}")
101
-
102
- # Search for specific groups
103
- dev_groups = api.lookup_groups("Dev")
104
- print("Development groups:", [group.friendly_name for group in dev_groups])
105
-
106
- # Get current user's group
107
- current_user_group = api.get_current_user_group()
108
- print("Current user's group:", current_user_group.friendly_name)
109
-
110
- # Create a new group
111
- new_group = Group(friendly_name="Data Science Team", description="Team working on ML projects")
112
- created_group = api.save_group(new_group)
113
- print("Created group:", created_group.friendly_name)
114
-
115
- # Get group members
116
- group_members = api.get_group_members(created_group.id)
117
- print(f"Members of {created_group.friendly_name}:", [m.friendly_name for m in group_members])
118
-
119
- # Get group memberships
120
- group_memberships = api.get_group_memberships(created_group.id)
121
- print(f"Memberships of {created_group.friendly_name}:", [m.friendly_name for m in group_memberships])
122
-
123
- # Request membership in a group
124
- request = api.request_group_membership(created_group.id)
125
- print("Membership request created:", request.id)
126
-
127
- # Get membership requests (as group admin)
128
- requests = api.get_group_membership_requests(created_group.id)
129
- for req in requests:
130
- print(f"Request from {req.from_group.friendly_name}: {'Approved' if req.is_approved else 'Pending'}")
131
-
132
- # Approve or deny requests (as group admin)
133
- if requests:
134
- if requests[0].from_group.friendly_name == "John Doe" and not requests[0].is_viewed:
135
- api.approve_membership_request(requests[0].id)
136
- else:
137
- api.deny_membership_request(requests[0].id)
138
-
139
- # Update group information
140
- created_group.description = "Updated description for Data Science Team"
141
- updated_group = api.save_group(created_group, save_relations=True)
142
- print("Updated group:", updated_group.friendly_name, updated_group.description)
143
-
144
- # Add Member Examples
145
-
146
- # Find John Doe's personal group
147
- john_doe_groups = api.lookup_groups("John Doe")
148
- john_doe_group = next((g for g in john_doe_groups if g.personal), None)
149
- if john_doe_group:
150
- print(f"Found John Doe's personal group: {john_doe_group.friendly_name}")
151
-
152
- # Add John Doe as regular member
153
- created_group.add_member(john_doe_group)
154
- print(f"Added {john_doe_group.friendly_name} as regular member to {created_group.friendly_name}")
155
-
156
- # Verify the member was added
157
- updated_group = api.get_group(created_group.id)
158
- print(f"Members after adding: {[m.friendly_name for m in updated_group.members]}")
159
-
160
- # Add John Doe as admin
161
- created_group.add_member(john_doe_group, is_admin=True)
162
- print(f"Added {john_doe_group.friendly_name} as admin to {created_group.friendly_name}")
163
-
164
- # Verify the admin member was added
165
- updated_group = api.get_group(created_group.id)
166
- print(f"Admin members: {[m.friendly_name for m in updated_group.admin_members]}")
167
- print(f"All members: {[m.friendly_name for m in updated_group.members]}")
168
- else:
169
- print("John Doe's personal group not found")
170
-
171
- ```
@@ -1,149 +0,0 @@
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
- # Group Management Examples
64
-
65
- # List all groups (excluding personal groups)
66
- groups = api.list_groups(include_personal=False)
67
- print("All groups:", [group.friendly_name for group in groups])
68
-
69
- # List groups with members and memberships
70
- groups_with_details = api.list_groups(
71
- include_personal=False,
72
- include_members=True,
73
- include_memberships=True
74
- )
75
- for group in groups_with_details:
76
- print(f"Group: {group.friendly_name}")
77
- print(f"Members: {[m.friendly_name for m in group.members]}")
78
- print(f"Memberships: {[m.friendly_name for m in group.memberships]}")
79
-
80
- # Search for specific groups
81
- dev_groups = api.lookup_groups("Dev")
82
- print("Development groups:", [group.friendly_name for group in dev_groups])
83
-
84
- # Get current user's group
85
- current_user_group = api.get_current_user_group()
86
- print("Current user's group:", current_user_group.friendly_name)
87
-
88
- # Create a new group
89
- new_group = Group(friendly_name="Data Science Team", description="Team working on ML projects")
90
- created_group = api.save_group(new_group)
91
- print("Created group:", created_group.friendly_name)
92
-
93
- # Get group members
94
- group_members = api.get_group_members(created_group.id)
95
- print(f"Members of {created_group.friendly_name}:", [m.friendly_name for m in group_members])
96
-
97
- # Get group memberships
98
- group_memberships = api.get_group_memberships(created_group.id)
99
- print(f"Memberships of {created_group.friendly_name}:", [m.friendly_name for m in group_memberships])
100
-
101
- # Request membership in a group
102
- request = api.request_group_membership(created_group.id)
103
- print("Membership request created:", request.id)
104
-
105
- # Get membership requests (as group admin)
106
- requests = api.get_group_membership_requests(created_group.id)
107
- for req in requests:
108
- print(f"Request from {req.from_group.friendly_name}: {'Approved' if req.is_approved else 'Pending'}")
109
-
110
- # Approve or deny requests (as group admin)
111
- if requests:
112
- if requests[0].from_group.friendly_name == "John Doe" and not requests[0].is_viewed:
113
- api.approve_membership_request(requests[0].id)
114
- else:
115
- api.deny_membership_request(requests[0].id)
116
-
117
- # Update group information
118
- created_group.description = "Updated description for Data Science Team"
119
- updated_group = api.save_group(created_group, save_relations=True)
120
- print("Updated group:", updated_group.friendly_name, updated_group.description)
121
-
122
- # Add Member Examples
123
-
124
- # Find John Doe's personal group
125
- john_doe_groups = api.lookup_groups("John Doe")
126
- john_doe_group = next((g for g in john_doe_groups if g.personal), None)
127
- if john_doe_group:
128
- print(f"Found John Doe's personal group: {john_doe_group.friendly_name}")
129
-
130
- # Add John Doe as regular member
131
- created_group.add_member(john_doe_group)
132
- print(f"Added {john_doe_group.friendly_name} as regular member to {created_group.friendly_name}")
133
-
134
- # Verify the member was added
135
- updated_group = api.get_group(created_group.id)
136
- print(f"Members after adding: {[m.friendly_name for m in updated_group.members]}")
137
-
138
- # Add John Doe as admin
139
- created_group.add_member(john_doe_group, is_admin=True)
140
- print(f"Added {john_doe_group.friendly_name} as admin to {created_group.friendly_name}")
141
-
142
- # Verify the admin member was added
143
- updated_group = api.get_group(created_group.id)
144
- print(f"Admin members: {[m.friendly_name for m in updated_group.admin_members]}")
145
- print(f"All members: {[m.friendly_name for m in updated_group.members]}")
146
- else:
147
- print("John Doe's personal group not found")
148
-
149
- ```
File without changes