datagrok-api 0.0.7__tar.gz → 0.0.9__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.
- {datagrok_api-0.0.7 → datagrok_api-0.0.9}/PKG-INFO +2 -1
- datagrok_api-0.0.9/datagrok_api/__init__.py +7 -0
- datagrok_api-0.0.9/datagrok_api/datagrok_client.py +107 -0
- datagrok_api-0.0.9/datagrok_api/http_client.py +76 -0
- datagrok_api-0.0.9/datagrok_api/models/__init__.py +14 -0
- datagrok_api-0.0.9/datagrok_api/models/data_connection.py +290 -0
- datagrok_api-0.0.9/datagrok_api/models/func.py +161 -0
- datagrok_api-0.0.9/datagrok_api/models/group.py +312 -0
- datagrok_api-0.0.9/datagrok_api/models/model.py +77 -0
- datagrok_api-0.0.9/datagrok_api/models/query.py +95 -0
- datagrok_api-0.0.9/datagrok_api/models/script.py +135 -0
- datagrok_api-0.0.9/datagrok_api/models/share_response.py +59 -0
- datagrok_api-0.0.9/datagrok_api/models/user.py +97 -0
- datagrok_api-0.0.9/datagrok_api/resources/__init__.py +12 -0
- datagrok_api-0.0.9/datagrok_api/resources/connections.py +158 -0
- datagrok_api-0.0.9/datagrok_api/resources/files.py +224 -0
- datagrok_api-0.0.9/datagrok_api/resources/functions.py +176 -0
- datagrok_api-0.0.9/datagrok_api/resources/groups.py +228 -0
- datagrok_api-0.0.9/datagrok_api/resources/shares.py +84 -0
- datagrok_api-0.0.9/datagrok_api/resources/tables.py +83 -0
- datagrok_api-0.0.9/datagrok_api/resources/users.py +135 -0
- {datagrok_api-0.0.7 → datagrok_api-0.0.9}/pyproject.toml +3 -2
- datagrok_api-0.0.7/datagrok_api/__init__.py +0 -4
- datagrok_api-0.0.7/datagrok_api/datagrok_client.py +0 -604
- datagrok_api-0.0.7/datagrok_api/group.py +0 -359
- datagrok_api-0.0.7/datagrok_api/model.py +0 -40
- {datagrok_api-0.0.7 → datagrok_api-0.0.9}/.gitignore +0 -0
- {datagrok_api-0.0.7 → datagrok_api-0.0.9}/README.md +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: datagrok-api
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.9
|
|
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
|
|
@@ -17,6 +17,7 @@ Requires-Dist: data-to-xml; extra == 'test'
|
|
|
17
17
|
Requires-Dist: pytest; extra == 'test'
|
|
18
18
|
Requires-Dist: pytest-item-dict; extra == 'test'
|
|
19
19
|
Requires-Dist: pytest-xml; extra == 'test'
|
|
20
|
+
Requires-Dist: requests-mock; extra == 'test'
|
|
20
21
|
Description-Content-Type: text/markdown
|
|
21
22
|
|
|
22
23
|
# Datagrok python client library
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
from datagrok_api.http_client import HttpClient
|
|
2
|
+
from datagrok_api.resources.connections import ConnectionsClient
|
|
3
|
+
from datagrok_api.resources.files import FilesClient
|
|
4
|
+
from datagrok_api.resources.functions import FunctionsClient
|
|
5
|
+
from datagrok_api.resources.groups import GroupsClient
|
|
6
|
+
from datagrok_api.resources.shares import SharesClient
|
|
7
|
+
from datagrok_api.resources.tables import TablesClient
|
|
8
|
+
from datagrok_api.resources.users import UsersClient
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DatagrokClient:
|
|
12
|
+
"""
|
|
13
|
+
A client for interacting with the Datagrok API.
|
|
14
|
+
|
|
15
|
+
This class provides convenient access to various Datagrok resources such as files, tables,
|
|
16
|
+
users, groups, functions, shares, and data connections. It handles authentication and wraps
|
|
17
|
+
lower-level HTTP calls with resource clients.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
base_url : str
|
|
22
|
+
The base URL of the Datagrok server (e.g., "https://public.datagrok.ai/api").
|
|
23
|
+
api_key : str
|
|
24
|
+
API key for authentication. It can be obtained from the Datagrok user profile page.
|
|
25
|
+
Should typically start with "Bearer ".
|
|
26
|
+
|
|
27
|
+
Attributes
|
|
28
|
+
----------
|
|
29
|
+
files : FilesClient
|
|
30
|
+
Access to file operations like upload, download, and sync.
|
|
31
|
+
functions : FunctionsClient
|
|
32
|
+
Allows calling and managing Datagrok functions.
|
|
33
|
+
groups : GroupsClient
|
|
34
|
+
Provides access to user and group management operations.
|
|
35
|
+
tables : TablesClient
|
|
36
|
+
Allows reading and uploading Datagrok tables (datasets).
|
|
37
|
+
shares : SharesClient
|
|
38
|
+
Manage entity sharing and permissions.
|
|
39
|
+
users : UsersClient
|
|
40
|
+
Provides information about platform users.
|
|
41
|
+
connections : ConnectionsClient
|
|
42
|
+
Interact with DataConnections (e.g., Postgres, Snowflake, S3, etc.).
|
|
43
|
+
|
|
44
|
+
Examples
|
|
45
|
+
--------
|
|
46
|
+
Initialize a client
|
|
47
|
+
|
|
48
|
+
>>> from datagrok_api import DatagrokClient
|
|
49
|
+
|
|
50
|
+
>>> grok = DatagrokClient(base_url="https://public.datagrok.ai/api", api_key="Bearer <your-token>")
|
|
51
|
+
|
|
52
|
+
Download table from server as pd.DataFrame
|
|
53
|
+
|
|
54
|
+
>>> tables = grok.tables.download("JohnDoe:MyTable")
|
|
55
|
+
|
|
56
|
+
Run a server-side function
|
|
57
|
+
|
|
58
|
+
>>> result = grok.functions.call("JohnDoe:MyFunction", {"a": 1, "b": 2})
|
|
59
|
+
>>> print(result)
|
|
60
|
+
|
|
61
|
+
Upload a local file
|
|
62
|
+
|
|
63
|
+
>>> uploaded_file = grok.files.upload("data.csv")
|
|
64
|
+
|
|
65
|
+
Get current user info
|
|
66
|
+
|
|
67
|
+
>>> me = grok.users.current()
|
|
68
|
+
>>> print(me.first_name)
|
|
69
|
+
|
|
70
|
+
Find and update a group
|
|
71
|
+
|
|
72
|
+
>>> group = grok.groups.find("Chemists")[0]
|
|
73
|
+
>>> group.description = "Updated description"
|
|
74
|
+
>>> grok.groups.save(group)
|
|
75
|
+
|
|
76
|
+
Create or modify a connection
|
|
77
|
+
|
|
78
|
+
>>> from datagrok_api.models import DataConnection, FileDataSourceType, Credentials
|
|
79
|
+
>>> creds = Credentials(accessKey="aws-key", secretKey="aws-secret")
|
|
80
|
+
>>> conn = DataConnection(name="My S3 Bucket", data_source=FileDataSourceType.S3, bucket="my-bucket", region="eu-west-1", credentials=creds)
|
|
81
|
+
>>> conn = grok.connections.save(conn)
|
|
82
|
+
|
|
83
|
+
Use as a context manager (auto closes session)
|
|
84
|
+
|
|
85
|
+
>>> with DatagrokClient("https://public.datagrok.ai/api", "Bearer <your-token>") as grok:
|
|
86
|
+
... print(grok.users.current().name)
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def __init__(self, base_url: str, api_key: str):
|
|
90
|
+
self._http = HttpClient(base_url=base_url, api_key=api_key)
|
|
91
|
+
self.files = FilesClient(client=self._http)
|
|
92
|
+
self.functions = FunctionsClient(client=self._http)
|
|
93
|
+
self.groups = GroupsClient(client=self._http)
|
|
94
|
+
self.tables = TablesClient(client=self._http)
|
|
95
|
+
self.shares = SharesClient(client=self._http)
|
|
96
|
+
self.users = UsersClient(client=self._http)
|
|
97
|
+
self.connections = ConnectionsClient(client=self._http)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def close(self):
|
|
101
|
+
self._http.close()
|
|
102
|
+
|
|
103
|
+
def __enter__(self):
|
|
104
|
+
return self
|
|
105
|
+
|
|
106
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
107
|
+
self.close()
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
from typing import Any, Dict, Optional
|
|
3
|
+
|
|
4
|
+
class HttpClient:
|
|
5
|
+
def __init__(self, base_url: str, api_key: str):
|
|
6
|
+
self.session = requests.Session()
|
|
7
|
+
self.base_url = base_url
|
|
8
|
+
self.session.headers.update({
|
|
9
|
+
'Authorization': api_key
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
def request(self, method: str, endpoint: str,
|
|
13
|
+
headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> requests.Response:
|
|
14
|
+
"""
|
|
15
|
+
Make an HTTP request to the Datagrok API.
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
method : str
|
|
20
|
+
HTTP method to use (e.g., "GET", "POST", "PUT", "DELETE").
|
|
21
|
+
endpoint : str
|
|
22
|
+
API endpoint path, relative to the base URL.
|
|
23
|
+
headers : dict of str to str, optional
|
|
24
|
+
Optional headers to include or override for this request.
|
|
25
|
+
**kwargs : Any
|
|
26
|
+
Additional arguments to pass to `requests.request`
|
|
27
|
+
(e.g., `params`, `json`, `data`, `files`, etc.).
|
|
28
|
+
|
|
29
|
+
Returns
|
|
30
|
+
-------
|
|
31
|
+
requests.Response
|
|
32
|
+
The response returned by the API.
|
|
33
|
+
|
|
34
|
+
Raises
|
|
35
|
+
------
|
|
36
|
+
Exception
|
|
37
|
+
If the API returns an error or if the response is not successful
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
url = f"{self.base_url}/{endpoint.lstrip('/')}"
|
|
41
|
+
merged_headers = {
|
|
42
|
+
'Content-Type': 'application/json',
|
|
43
|
+
**self.session.headers,
|
|
44
|
+
**(headers or {}),
|
|
45
|
+
}
|
|
46
|
+
response = self.session.request(method, url, headers=merged_headers, **kwargs)
|
|
47
|
+
response.raise_for_status()
|
|
48
|
+
if 'api-error' in response.headers:
|
|
49
|
+
content = response.content.decode()
|
|
50
|
+
if 'ApiError' in content:
|
|
51
|
+
raise Exception(content)
|
|
52
|
+
else:
|
|
53
|
+
raise Exception("Something went wrong during request")
|
|
54
|
+
return response
|
|
55
|
+
|
|
56
|
+
def get(self, endpoint: str,
|
|
57
|
+
headers: Optional[Dict[str, str]] = None, **kwargs: Any):
|
|
58
|
+
return self.request('GET', endpoint, headers=headers, **kwargs)
|
|
59
|
+
|
|
60
|
+
def post(self, endpoint: str,
|
|
61
|
+
headers: Optional[Dict[str, str]] = None, **kwargs: Any):
|
|
62
|
+
return self.request('POST', endpoint, headers=headers, **kwargs)
|
|
63
|
+
|
|
64
|
+
def delete(self, endpoint: str,
|
|
65
|
+
headers: Optional[Dict[str, str]] = None, **kwargs: Any):
|
|
66
|
+
return self.request('DELETE', endpoint, headers=headers, **kwargs)
|
|
67
|
+
|
|
68
|
+
def close(self):
|
|
69
|
+
self.session.close()
|
|
70
|
+
|
|
71
|
+
def __enter__(self):
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
75
|
+
self.close()
|
|
76
|
+
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from .user import User
|
|
2
|
+
from .group import Group
|
|
3
|
+
from .query import DataQuery
|
|
4
|
+
from .script import Script, ScriptLanguage
|
|
5
|
+
from .func import Func, FuncParam, PropertyType
|
|
6
|
+
from .model import Model
|
|
7
|
+
from .data_connection import DataConnection, Credentials, DatabaseDataSourceType, FileDataSourceType, DataSourceType
|
|
8
|
+
from .share_response import ShareResponse
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"User", "Group", "DataQuery", "Script", "ScriptLanguage",
|
|
12
|
+
"Func", "FuncParam", "PropertyType", "Model", "DataConnection", "ShareResponse",
|
|
13
|
+
"DatabaseDataSourceType", "Credentials", "FileDataSourceType", "DataSourceType"
|
|
14
|
+
]
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
from typing import List, Optional, Union
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from datagrok_api.models.model import Model, NamedModel
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class DataSourceType(str, Enum):
|
|
8
|
+
@classmethod
|
|
9
|
+
def is_file_data_source(cls, source: Union[str, 'DataSourceType']) -> bool:
|
|
10
|
+
if isinstance(source, Enum):
|
|
11
|
+
source = source.value
|
|
12
|
+
return source in FileDataSourceType._value2member_map_
|
|
13
|
+
|
|
14
|
+
@classmethod
|
|
15
|
+
def is_database_data_source(cls, source: Union[str, 'DataSourceType']) -> bool:
|
|
16
|
+
if isinstance(source, Enum):
|
|
17
|
+
source = source.value
|
|
18
|
+
return source in DatabaseDataSourceType._value2member_map_
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def is_system(cls, source: Union[str, 'DataSourceType']) -> bool:
|
|
22
|
+
if isinstance(source, Enum):
|
|
23
|
+
source = source.value
|
|
24
|
+
return source in {
|
|
25
|
+
DatabaseDataSourceType.AWSSM.value,
|
|
26
|
+
DatabaseDataSourceType.PostgresDart.value,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def can_be_tested(cls, source: Union[str, 'DataSourceType']) -> bool:
|
|
31
|
+
if isinstance(source, Enum):
|
|
32
|
+
source = source.value
|
|
33
|
+
return source != DatabaseDataSourceType.AWSSM.value
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def from_str(cls, value: str) -> "DataSourceType":
|
|
37
|
+
if DataSourceType.is_file_data_source(value):
|
|
38
|
+
return FileDataSourceType(value)
|
|
39
|
+
elif DataSourceType.is_database_data_source(value):
|
|
40
|
+
return DatabaseDataSourceType(value)
|
|
41
|
+
else:
|
|
42
|
+
raise ValueError(f"Unknown datasource type {value}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class FileDataSourceType(DataSourceType):
|
|
46
|
+
AzureBlob = 'Azure Blob'
|
|
47
|
+
Dropbox = 'Dropbox'
|
|
48
|
+
GitHub = 'GitHub'
|
|
49
|
+
GoogleCloud = 'GoogleCloud'
|
|
50
|
+
S3 = 'S3'
|
|
51
|
+
EFS = 'Amazon EFS'
|
|
52
|
+
SharePoint = 'SharePoint'
|
|
53
|
+
Files = 'Files'
|
|
54
|
+
CoreWeave = 'CoreWeave'
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class DatabaseDataSourceType(DataSourceType):
|
|
58
|
+
Access = 'Access'
|
|
59
|
+
Athena = 'Athena'
|
|
60
|
+
BigQuery = 'BigQuery'
|
|
61
|
+
Cassandra = 'Cassandra'
|
|
62
|
+
DB2 = 'DB2'
|
|
63
|
+
Excel = 'Excel'
|
|
64
|
+
Firebird = 'Firebird'
|
|
65
|
+
HBase = 'HBase'
|
|
66
|
+
Hive = 'Hive'
|
|
67
|
+
Hive2 = 'Hive2'
|
|
68
|
+
MariaDB = 'MariaDB'
|
|
69
|
+
MlFlow = 'MLFlow'
|
|
70
|
+
MongoDB = 'MongoDB'
|
|
71
|
+
MsSql = 'MS SQL'
|
|
72
|
+
MySql = 'MySQL'
|
|
73
|
+
Neo4j = 'Neo4j'
|
|
74
|
+
Oracle = 'Oracle'
|
|
75
|
+
PostgresDart = 'PostgresDart'
|
|
76
|
+
ClickHouse = 'ClickHouse'
|
|
77
|
+
Postgres = 'Postgres'
|
|
78
|
+
Redshift = 'Redshift'
|
|
79
|
+
Snowflake = 'Snowflake'
|
|
80
|
+
SQLite = 'SQLite'
|
|
81
|
+
Socrata = 'Socrata'
|
|
82
|
+
Sparql = 'Sparql'
|
|
83
|
+
Teradata = 'Teradata'
|
|
84
|
+
Twitter = 'Twitter'
|
|
85
|
+
Vertica = 'Vertica'
|
|
86
|
+
Web = 'Web'
|
|
87
|
+
AWSSM = 'AWS'
|
|
88
|
+
|
|
89
|
+
class Credentials(Model):
|
|
90
|
+
"""
|
|
91
|
+
Holds authentication credentials for a data connection.
|
|
92
|
+
|
|
93
|
+
Allows dynamic setting and getting of credential fields like login, password,
|
|
94
|
+
access keys, or tokens depending on the data source.
|
|
95
|
+
|
|
96
|
+
Attributes
|
|
97
|
+
----------
|
|
98
|
+
**kwargs : dict
|
|
99
|
+
Arbitrary credential fields passed as key-value pairs.
|
|
100
|
+
|
|
101
|
+
Examples
|
|
102
|
+
--------
|
|
103
|
+
Create Credentials with login and password
|
|
104
|
+
|
|
105
|
+
>>> creds = Credentials(login="postgres", password="postgres")
|
|
106
|
+
>>> print(creds.login) # Access login
|
|
107
|
+
>>> creds.password = "new_pass" # Update password dynamically
|
|
108
|
+
|
|
109
|
+
Create Credentials with AWS access keys
|
|
110
|
+
|
|
111
|
+
>>> aws_creds = Credentials(access_key="AKIA...", secret_key="...")
|
|
112
|
+
>>> print(aws_creds.access_key) # Access AWS access key
|
|
113
|
+
>>> aws_creds.secret_key = "NEW_SECRET" # Update secret key dynamically
|
|
114
|
+
"""
|
|
115
|
+
_explicit_attrs = {"id", "parameters", "open_parameters"}
|
|
116
|
+
def __init__(self, **kwargs):
|
|
117
|
+
super().__init__(None)
|
|
118
|
+
self.parameters = dict(kwargs)
|
|
119
|
+
self.open_parameters = dict()
|
|
120
|
+
|
|
121
|
+
def get(self, key, default=None):
|
|
122
|
+
return self.parameters.get(key, default)
|
|
123
|
+
|
|
124
|
+
def to_dict(self):
|
|
125
|
+
return {
|
|
126
|
+
"id": self.id,
|
|
127
|
+
"parameters": self.parameters,
|
|
128
|
+
"openParameters": self.open_parameters
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
def from_dict(cls, data: dict) -> 'Credentials':
|
|
133
|
+
creds = cls(**data.get('parameters', {}))
|
|
134
|
+
creds.id = data.get('id')
|
|
135
|
+
creds.open_parameters = data.get('openParameters', {})
|
|
136
|
+
return creds
|
|
137
|
+
|
|
138
|
+
def __getattr__(self, name):
|
|
139
|
+
if name in self.parameters:
|
|
140
|
+
return self.parameters[name]
|
|
141
|
+
raise AttributeError(f"'Credentials' object has no attribute '{name}'")
|
|
142
|
+
|
|
143
|
+
def __getitem__(self, key):
|
|
144
|
+
return self.parameters[key]
|
|
145
|
+
|
|
146
|
+
def __setitem__(self, key, value):
|
|
147
|
+
self.parameters[key] = value
|
|
148
|
+
|
|
149
|
+
def __setattr__(self, name, value):
|
|
150
|
+
if name in Credentials._explicit_attrs:
|
|
151
|
+
object.__setattr__(self, name, value)
|
|
152
|
+
else:
|
|
153
|
+
self.parameters[name] = value
|
|
154
|
+
|
|
155
|
+
class DataConnection(NamedModel):
|
|
156
|
+
"""
|
|
157
|
+
Represents a data connection in Datagrok.
|
|
158
|
+
|
|
159
|
+
Attributes
|
|
160
|
+
----------
|
|
161
|
+
name : Optional[str]
|
|
162
|
+
Internal name of the model, used as an identifier.
|
|
163
|
+
id : Optional[str]
|
|
164
|
+
Unique identifier for the model instance. Can be None for new instances.
|
|
165
|
+
friendly_name : Optional[str]
|
|
166
|
+
Human-readable name for display purposes. Defaults to None.
|
|
167
|
+
created_on : Optional[datetime]
|
|
168
|
+
Timestamp indicating when the model was created. Defaults to None.
|
|
169
|
+
updated_on : Optional[datetime]
|
|
170
|
+
Timestamp indicating when the model was last updated. Defaults to None.
|
|
171
|
+
namespace : Optional[str]
|
|
172
|
+
Optional namespace prefix to distinguish models with the same name. Defaults to None.
|
|
173
|
+
data_source : DataSourceType
|
|
174
|
+
Type of data source this connection uses.
|
|
175
|
+
description : Optional[str]
|
|
176
|
+
Optional textual description of the data connection.
|
|
177
|
+
credentials : Optional[Credentials]
|
|
178
|
+
Authentication credentials used to access the data source.
|
|
179
|
+
tags : Optional[List[str]]
|
|
180
|
+
List of tags associated with the connection for categorization.
|
|
181
|
+
**kwargs : dict
|
|
182
|
+
Additional arbitrary parameters stored in the `parameters` dictionary.
|
|
183
|
+
|
|
184
|
+
Examples
|
|
185
|
+
--------
|
|
186
|
+
Create a connection to a Postgres database with login parameters
|
|
187
|
+
|
|
188
|
+
>>> conn_pg = DataConnection(
|
|
189
|
+
... name="my_postgres_conn",
|
|
190
|
+
... data_source=DataSourceType.Postgres,
|
|
191
|
+
... server="localhost",
|
|
192
|
+
... port=5432,
|
|
193
|
+
... db="mydb",
|
|
194
|
+
... new Credentials(login="postgres", password="postgres")
|
|
195
|
+
... )
|
|
196
|
+
>>> print(conn_pg.host) # Access arbitrary parameter
|
|
197
|
+
>>> conn_pg.password = "new_password" # Update arbitrary parameter
|
|
198
|
+
|
|
199
|
+
Create a connection to an S3 bucket with different parameters
|
|
200
|
+
|
|
201
|
+
>>> conn_s3 = DataConnection(
|
|
202
|
+
... name="my_s3_conn",
|
|
203
|
+
... data_source=DataSourceType.S3,
|
|
204
|
+
... bucket="my-bucket",
|
|
205
|
+
... region="us-west-2",
|
|
206
|
+
... new Credentials(accessKey="AKIA...", secretKey="...")
|
|
207
|
+
... )
|
|
208
|
+
>>> print(conn_s3.bucket) # Access bucket name
|
|
209
|
+
>>> conn_s3.region = "us-east-1" # Update region dynamically
|
|
210
|
+
"""
|
|
211
|
+
def __init__(self,
|
|
212
|
+
name: str,
|
|
213
|
+
data_source: DataSourceType,
|
|
214
|
+
id: Optional[str] = None,
|
|
215
|
+
friendly_name: Optional[str] = None,
|
|
216
|
+
description: Optional[str] = None,
|
|
217
|
+
credentials: Optional[Credentials] = None,
|
|
218
|
+
tags: Optional[List[str]] = None,
|
|
219
|
+
created_on: Optional[datetime] = None,
|
|
220
|
+
updated_on: Optional[datetime] = None,
|
|
221
|
+
namespace: Optional[str] = None,
|
|
222
|
+
**kwargs):
|
|
223
|
+
super().__init__(id=id, name=name, friendly_name=friendly_name, created_on=created_on, updated_on=updated_on, namespace=namespace)
|
|
224
|
+
self.data_source = data_source
|
|
225
|
+
self.description = description
|
|
226
|
+
self.credentials = credentials or Credentials()
|
|
227
|
+
self.tags = tags or []
|
|
228
|
+
self.parameters = dict(kwargs)
|
|
229
|
+
|
|
230
|
+
_explicit_attrs = {"id", "name", "data_source", "friendly_name", "description", "credentials", "parameters", "tags", "created_on", "updated_on", "namespace"}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def get(self, key, default=None):
|
|
234
|
+
return self.parameters.get(key, default)
|
|
235
|
+
|
|
236
|
+
def to_dict(self):
|
|
237
|
+
return {
|
|
238
|
+
"id": self.id,
|
|
239
|
+
"parameters": self.parameters,
|
|
240
|
+
"name": self.name,
|
|
241
|
+
"friendlyName": self.friendly_name,
|
|
242
|
+
"description": self.description,
|
|
243
|
+
"dataSource": self.data_source.value,
|
|
244
|
+
"credentials": self.credentials.to_dict(),
|
|
245
|
+
"createdOn": self.created_on.isoformat() if self.created_on else None,
|
|
246
|
+
"updatedOn": self.updated_on.isoformat() if self.updated_on else None,
|
|
247
|
+
"tags": self.tags,
|
|
248
|
+
"namespace": self.namespace
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
@classmethod
|
|
253
|
+
def from_dict(cls, data: dict) -> 'DataConnection':
|
|
254
|
+
credentials = Credentials.from_dict(data.get('credentials', {}))
|
|
255
|
+
conn = cls(
|
|
256
|
+
name=data.get("name") or "",
|
|
257
|
+
data_source=DataSourceType.from_str(data.get("dataSource") if data.get("dataSource") else FileDataSourceType.Files),
|
|
258
|
+
id=data.get("id"),
|
|
259
|
+
friendly_name=data.get("friendlyName"),
|
|
260
|
+
description=data.get("description"),
|
|
261
|
+
credentials=credentials,
|
|
262
|
+
tags=data.get('tags', []),
|
|
263
|
+
namespace=data.get("namespace"),
|
|
264
|
+
**data.get("parameters", {})
|
|
265
|
+
)
|
|
266
|
+
created_str = data.get("createdOn")
|
|
267
|
+
conn.created_on = datetime.fromisoformat(created_str) if created_str else None
|
|
268
|
+
|
|
269
|
+
updated_str = data.get("updatedOn")
|
|
270
|
+
conn.updated_on = datetime.fromisoformat(updated_str) if updated_str else None
|
|
271
|
+
|
|
272
|
+
return conn
|
|
273
|
+
|
|
274
|
+
def __getattr__(self, name):
|
|
275
|
+
parameters = object.__getattribute__(self, 'parameters')
|
|
276
|
+
if name in parameters:
|
|
277
|
+
return parameters[name]
|
|
278
|
+
raise AttributeError(f"'DataConnection' parameters has no attribute '{name}'")
|
|
279
|
+
|
|
280
|
+
def __getitem__(self, key):
|
|
281
|
+
return self.parameters[key]
|
|
282
|
+
|
|
283
|
+
def __setitem__(self, key, value):
|
|
284
|
+
self.parameters[key] = value
|
|
285
|
+
|
|
286
|
+
def __setattr__(self, name, value):
|
|
287
|
+
if name in DataConnection._explicit_attrs:
|
|
288
|
+
object.__setattr__(self, name, value)
|
|
289
|
+
else:
|
|
290
|
+
self.parameters[name] = value
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from enum import Enum
|
|
3
|
+
from typing import Optional, Any, Dict, List, Type
|
|
4
|
+
from datagrok_api.models.model import NamedModel
|
|
5
|
+
|
|
6
|
+
class PropertyType(str, Enum):
|
|
7
|
+
INT = 'int'
|
|
8
|
+
STRING = 'string'
|
|
9
|
+
BOOL = 'bool'
|
|
10
|
+
FLOAT = 'double'
|
|
11
|
+
BIG_INT = 'bigint'
|
|
12
|
+
DATA_FRAME = 'dataframe'
|
|
13
|
+
DATE_TIME = 'datetime'
|
|
14
|
+
FILE = 'file'
|
|
15
|
+
BLOB = 'blob'
|
|
16
|
+
COLUMN = 'column'
|
|
17
|
+
COLUMN_LIST = 'column_list'
|
|
18
|
+
GRAPHICS = 'graphics'
|
|
19
|
+
DYNAMIC = 'dynamic'
|
|
20
|
+
|
|
21
|
+
class FuncParam:
|
|
22
|
+
def __init__(self, name: str, type: PropertyType, is_input: bool = True):
|
|
23
|
+
self.name = name
|
|
24
|
+
self.type = type
|
|
25
|
+
self.is_input = is_input
|
|
26
|
+
|
|
27
|
+
def to_dict(self):
|
|
28
|
+
return {
|
|
29
|
+
"name": self.name,
|
|
30
|
+
"propertyType": self.type,
|
|
31
|
+
"isInput": self.is_input
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
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))
|
|
37
|
+
|
|
38
|
+
class Func(NamedModel):
|
|
39
|
+
"""
|
|
40
|
+
Represents a function in the Datagrok platform.
|
|
41
|
+
|
|
42
|
+
In Grok, nearly every executable action—whether it's a data query,
|
|
43
|
+
a script, a UI action, or a predictive model—is represented as a
|
|
44
|
+
`Func`. This unified abstraction provides a consistent way to
|
|
45
|
+
define, discover, secure, and execute platform capabilities.
|
|
46
|
+
|
|
47
|
+
Examples of functions in Grok include:
|
|
48
|
+
* Querying an external PostgreSQL database
|
|
49
|
+
* Executing JavaScript code in the browser that uses Grok APIs
|
|
50
|
+
* Performing mathematical calculations (e.g., `Sin(PI)`)
|
|
51
|
+
* Modifying datasets (e.g., deleting a column)
|
|
52
|
+
* Sending an email
|
|
53
|
+
* Applying a predictive model to a dataset
|
|
54
|
+
* Calculating molecular properties via a Python script
|
|
55
|
+
* Displaying interactive dialogs
|
|
56
|
+
|
|
57
|
+
Despite their differences (server-side vs client-side execution,
|
|
58
|
+
computational vs UI-based tasks), all functions share a common
|
|
59
|
+
set of capabilities:
|
|
60
|
+
* **Scriptable**: Callable from the console or scripts.
|
|
61
|
+
* **Findable**: Searchable through the "Help | Functions" interface.
|
|
62
|
+
* **Introspectable**: Metadata about parameters is programmatically accessible.
|
|
63
|
+
* **Secure**: Access can be restricted via privileges or user groups.
|
|
64
|
+
* **Auditable**: Execution history and parameters are tracked.
|
|
65
|
+
* **Runnable**: The platform can dynamically generate UI for parameters.
|
|
66
|
+
* **Linkable**: Functions can be linked in dashboards, conversations, etc.
|
|
67
|
+
* **Composable**: Usable in workflow designers and query transformations.
|
|
68
|
+
|
|
69
|
+
Attributes
|
|
70
|
+
----------
|
|
71
|
+
source : Optional[str], default='function'
|
|
72
|
+
Identifies the origin or type of function (e.g., `"function"`, `"sql-query"`, `"js-script"`).
|
|
73
|
+
options : Optional[Dict[str, Any]], default=None
|
|
74
|
+
Arbitrary function-specific configuration options.
|
|
75
|
+
tags : Optional[List[str]], default=None
|
|
76
|
+
Keywords or categories associated with the function.
|
|
77
|
+
description : Optional[str], default=None
|
|
78
|
+
A human-readable description of the function's purpose.
|
|
79
|
+
params : Optional[List[FuncParam]], default=None
|
|
80
|
+
List of parameter definitions for the function.
|
|
81
|
+
**kwargs
|
|
82
|
+
Additional arguments passed to the parent `NamedModel` initializer,
|
|
83
|
+
such as `id`, `name`, `friendly_name`, `created_on`, `updated_on`, and `namespace`.
|
|
84
|
+
params : list of FuncParam
|
|
85
|
+
Parameter definitions (both input and output).
|
|
86
|
+
source : str
|
|
87
|
+
Function type or origin.
|
|
88
|
+
tags : list of str
|
|
89
|
+
Function categories or keywords.
|
|
90
|
+
description : str
|
|
91
|
+
Human-readable description.
|
|
92
|
+
options : dict
|
|
93
|
+
Function-specific settings.
|
|
94
|
+
input_params : list of FuncParam
|
|
95
|
+
Parameters marked as inputs to the function.
|
|
96
|
+
output_params : list of FuncParam
|
|
97
|
+
Parameters marked as outputs from the function.
|
|
98
|
+
"""
|
|
99
|
+
SOURCE = "function"
|
|
100
|
+
_registry: Dict[str, Type["Func"]] = {}
|
|
101
|
+
|
|
102
|
+
def __init__(self, source: Optional[str] = 'function', options: Optional[Dict[str, Any]] = None, tags: Optional[List[str]] = None, description: Optional[str]=None, params: Optional[List[FuncParam]] = None, **kwargs):
|
|
103
|
+
super().__init__(**kwargs)
|
|
104
|
+
self.params = params or []
|
|
105
|
+
self.source = source
|
|
106
|
+
self.tags = tags or []
|
|
107
|
+
self.description = description
|
|
108
|
+
self.options = options or dict()
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def input_params(self):
|
|
112
|
+
return [x for x in self.params if x.is_input]
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def output_params(self):
|
|
116
|
+
return [x for x in self.params if not x.is_input]
|
|
117
|
+
|
|
118
|
+
def to_dict(self):
|
|
119
|
+
return {
|
|
120
|
+
"id": self.id,
|
|
121
|
+
"name": self.name,
|
|
122
|
+
'friendlyName': self.friendly_name,
|
|
123
|
+
"createdOn": self.created_on.isoformat() if self.created_on else None,
|
|
124
|
+
"updatedOn": self.updated_on.isoformat() if self.updated_on else None,
|
|
125
|
+
"source": self.source,
|
|
126
|
+
"description": self.description,
|
|
127
|
+
"params": [param.to_dict() for param in self.params],
|
|
128
|
+
"namespace": self.namespace,
|
|
129
|
+
"tags": self.tags,
|
|
130
|
+
"options": self.options
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
@classmethod
|
|
134
|
+
def register_subclass(cls, source: str):
|
|
135
|
+
def decorator(subclass):
|
|
136
|
+
Func._registry[source] = subclass
|
|
137
|
+
return subclass
|
|
138
|
+
return decorator
|
|
139
|
+
|
|
140
|
+
@classmethod
|
|
141
|
+
def from_dict(cls, data: dict) -> "Func":
|
|
142
|
+
source = data.get("source")
|
|
143
|
+
subclass = Func._registry.get(source, cls)
|
|
144
|
+
return subclass._from_dict(data)
|
|
145
|
+
|
|
146
|
+
@classmethod
|
|
147
|
+
def _from_dict(cls, data: dict) -> "Func":
|
|
148
|
+
return cls(
|
|
149
|
+
id=data.get("id"),
|
|
150
|
+
name=data.get("name"),
|
|
151
|
+
friendly_name=data.get("friendlyName"),
|
|
152
|
+
description=data.get("description"),
|
|
153
|
+
created_on=datetime.fromisoformat(data["createdOn"]) if data.get("createdOn") else None,
|
|
154
|
+
updated_on=datetime.fromisoformat(data["updatedOn"]) if data.get("updatedOn") else None,
|
|
155
|
+
source=data.get("source"),
|
|
156
|
+
params=[FuncParam.from_dict(d) for d in data.get("params")] if data.get("params") else [],
|
|
157
|
+
namespace=data.get("namespace"),
|
|
158
|
+
tags=data.get('tags', []),
|
|
159
|
+
options=data.get("options")
|
|
160
|
+
)
|
|
161
|
+
|