Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
singlestore-labs
GitHub Repository: singlestore-labs/singlestoredb-python
Path: blob/main/singlestoredb/management/organization.py
469 views
1
#!/usr/bin/env python
2
"""SingleStoreDB Cloud Organization."""
3
import datetime
4
from typing import Dict
5
from typing import List
6
from typing import Optional
7
from typing import Union
8
9
from ..exceptions import ManagementError
10
from .inference_api import InferenceAPIManager
11
from .job import JobsManager
12
from .manager import Manager
13
from .utils import vars_to_str
14
15
16
def listify(x: Union[str, List[str]]) -> List[str]:
17
if isinstance(x, list):
18
return x
19
return [x]
20
21
22
def stringify(x: Union[str, List[str]]) -> str:
23
if isinstance(x, list):
24
return x[0]
25
return x
26
27
28
class Secret(object):
29
"""
30
SingleStoreDB secrets definition.
31
32
This object is not directly instantiated. It is used in results
33
of API calls on the :class:`Organization`. See :meth:`Organization.get_secret`.
34
"""
35
36
def __init__(
37
self,
38
id: str,
39
name: str,
40
created_by: str,
41
created_at: Union[str, datetime.datetime],
42
last_updated_by: str,
43
last_updated_at: Union[str, datetime.datetime],
44
value: Optional[str] = None,
45
deleted_by: Optional[str] = None,
46
deleted_at: Optional[Union[str, datetime.datetime]] = None,
47
):
48
# UUID of the secret
49
self.id = id
50
51
# Name of the secret
52
self.name = name
53
54
# Value of the secret
55
self.value = value
56
57
# User who created the secret
58
self.created_by = created_by
59
60
# Time when the secret was created
61
self.created_at = created_at
62
63
# UUID of the user who last updated the secret
64
self.last_updated_by = last_updated_by
65
66
# Time when the secret was last updated
67
self.last_updated_at = last_updated_at
68
69
# UUID of the user who deleted the secret
70
self.deleted_by = deleted_by
71
72
# Time when the secret was deleted
73
self.deleted_at = deleted_at
74
75
@classmethod
76
def from_dict(cls, obj: Dict[str, str]) -> 'Secret':
77
"""
78
Construct a Secret from a dictionary of values.
79
80
Parameters
81
----------
82
obj : dict
83
Dictionary of values
84
85
Returns
86
-------
87
:class:`Secret`
88
89
"""
90
out = cls(
91
id=obj['secretID'],
92
name=obj['name'],
93
created_by=obj['createdBy'],
94
created_at=obj['createdAt'],
95
last_updated_by=obj['lastUpdatedBy'],
96
last_updated_at=obj['lastUpdatedAt'],
97
value=obj.get('value'),
98
deleted_by=obj.get('deletedBy'),
99
deleted_at=obj.get('deletedAt'),
100
)
101
102
return out
103
104
def __str__(self) -> str:
105
"""Return string representation."""
106
return vars_to_str(self)
107
108
def __repr__(self) -> str:
109
"""Return string representation."""
110
return str(self)
111
112
113
class Organization(object):
114
"""
115
Organization in SingleStoreDB Cloud portal.
116
117
This object is not directly instantiated. It is used in results
118
of ``WorkspaceManager`` API calls.
119
120
See Also
121
--------
122
:attr:`WorkspaceManager.organization`
123
124
"""
125
126
id: str
127
name: str
128
firewall_ranges: List[str]
129
130
def __init__(self, id: str, name: str, firewall_ranges: List[str]):
131
"""Use :attr:`WorkspaceManager.organization` instead."""
132
#: Unique ID of the organization
133
self.id = id
134
135
#: Name of the organization
136
self.name = name
137
138
#: Firewall ranges of the organization
139
self.firewall_ranges = list(firewall_ranges)
140
141
self._manager: Optional[Manager] = None
142
143
def __str__(self) -> str:
144
"""Return string representation."""
145
return vars_to_str(self)
146
147
def __repr__(self) -> str:
148
"""Return string representation."""
149
return str(self)
150
151
def get_secret(self, name: str) -> Secret:
152
if self._manager is None:
153
raise ManagementError(msg='Organization not initialized')
154
155
res = self._manager._get('secrets', params=dict(name=name))
156
157
secrets = [Secret.from_dict(item) for item in res.json()['secrets']]
158
159
if len(secrets) == 0:
160
raise ManagementError(msg=f'Secret {name} not found')
161
162
if len(secrets) > 1:
163
raise ManagementError(msg=f'Multiple secrets found for {name}')
164
165
return secrets[0]
166
167
@classmethod
168
def from_dict(
169
cls,
170
obj: Dict[str, Union[str, List[str]]],
171
manager: Manager,
172
) -> 'Organization':
173
"""
174
Convert dictionary to an ``Organization`` object.
175
176
Parameters
177
----------
178
obj : dict
179
Key-value pairs to retrieve organization information from
180
manager : WorkspaceManager, optional
181
The WorkspaceManager the Organization belongs to
182
183
Returns
184
-------
185
:class:`Organization`
186
187
"""
188
out = cls(
189
id=stringify(obj['orgID']),
190
name=stringify(obj.get('name', '<unknown>')),
191
firewall_ranges=listify(obj.get('firewallRanges', [])),
192
)
193
out._manager = manager
194
return out
195
196
@property
197
def jobs(self) -> JobsManager:
198
"""
199
Retrieve a SingleStoreDB scheduled job manager.
200
201
Parameters
202
----------
203
manager : WorkspaceManager, optional
204
The WorkspaceManager the JobsManager belongs to
205
206
Returns
207
-------
208
:class:`JobsManager`
209
"""
210
return JobsManager(self._manager)
211
212
@property
213
def inference_apis(self) -> InferenceAPIManager:
214
"""
215
Retrieve a SingleStoreDB inference api manager.
216
217
Parameters
218
----------
219
manager : WorkspaceManager, optional
220
The WorkspaceManager the InferenceAPIManager belongs to
221
222
Returns
223
-------
224
:class:`InferenceAPIManager`
225
"""
226
return InferenceAPIManager(self._manager)
227
228