-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathusers.py
More file actions
256 lines (192 loc) · 9.26 KB
/
Copy pathusers.py
File metadata and controls
256 lines (192 loc) · 9.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
from __future__ import annotations
from collections.abc import AsyncIterator, Sequence
from typing import TYPE_CHECKING, overload
from cognite.client._api_client import APIClient
from cognite.client.constants import DEFAULT_LIMIT_READ
from cognite.client.data_classes.postgres_gateway.users import (
User,
UserCreated,
UserCreatedList,
UserList,
UserUpdate,
UserWrite,
)
from cognite.client.utils._identifier import UsernameSequence
from cognite.client.utils.useful_types import SequenceNotStr
if TYPE_CHECKING:
from cognite.client import AsyncCogniteClient, ClientConfig
class UsersAPI(APIClient):
_RESOURCE_PATH = "/postgresgateway"
def __init__(self, config: ClientConfig, api_version: str | None, cognite_client: AsyncCogniteClient) -> None:
super().__init__(config, api_version, cognite_client)
self._CREATE_LIMIT = 1
self._UPDATE_LIMIT = 1
self._DELETE_LIMIT = 1
self._LIST_LIMIT = 100
self._RETRIEVE_LIMIT = 10
@overload
def __call__(self, chunk_size: None = None, limit: int | None = None) -> AsyncIterator[User]: ...
@overload
def __call__(self, chunk_size: int, limit: int | None = None) -> AsyncIterator[UserList]: ...
async def __call__(
self, chunk_size: int | None = None, limit: int | None = None
) -> AsyncIterator[User] | AsyncIterator[UserList]:
"""Iterate over users
Fetches user as they are iterated over, so you keep a limited number of users in memory.
Args:
chunk_size (int | None): Number of users to return in each chunk. Defaults to yielding one user at a time.
limit (int | None): Maximum number of users to return. Defaults to return all.
Yields:
User | UserList: yields User one by one if chunk_size is not specified, else UserList objects.
""" # noqa: DOC404
async for item in self._list_generator(
list_cls=UserList,
resource_cls=User,
method="GET",
chunk_size=chunk_size,
limit=limit,
):
yield item
@overload
async def create(self, user: UserWrite) -> UserCreated: ...
@overload
async def create(self, user: Sequence[UserWrite]) -> UserCreatedList: ...
async def create(self, user: UserWrite | Sequence[UserWrite]) -> UserCreated | UserCreatedList:
"""`Create Users <https://api-docs.cognite.com/20230101-beta/tag/Postgres-Gateway-Users/operation/create_users>`_.
Create postgres users.
Args:
user (UserWrite | Sequence[UserWrite]): The user(s) to create.
Returns:
UserCreated | UserCreatedList: The created user(s)
Examples:
Create user:
>>> import os
>>> from cognite.client import CogniteClient
>>> from cognite.client.data_classes.postgres_gateway import (
... UserWrite,
... SessionCredentials,
... )
>>> from cognite.client.data_classes import ClientCredentials
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> session = client.iam.sessions.create(
... ClientCredentials(os.environ["IDP_CLIENT_ID"], os.environ["IDP_CLIENT_SECRET"]),
... session_type="CLIENT_CREDENTIALS",
... )
>>> user = UserWrite(credentials=SessionCredentials(nonce=session.nonce))
>>> res = client.postgres_gateway.users.create(user)
"""
return await self._create_multiple(
list_cls=UserCreatedList,
resource_cls=UserCreated,
items=user,
input_resource_cls=UserWrite,
)
@overload
async def update(self, items: UserUpdate | UserWrite) -> User: ...
@overload
async def update(self, items: Sequence[UserUpdate | UserWrite]) -> UserList: ...
async def update(self, items: UserUpdate | UserWrite | Sequence[UserUpdate | UserWrite]) -> User | UserList:
"""`Update users <https://api-docs.cognite.com/20230101-beta/tag/Postgres-Gateway-Users/operation/update_users>`_.
Update postgres users
Args:
items (UserUpdate | UserWrite | Sequence[UserUpdate | UserWrite]): The user(s) to update.
Returns:
User | UserList: The updated user(s)
Examples:
Update user:
>>> import os
>>> from cognite.client import CogniteClient
>>> from cognite.client.data_classes.postgres_gateway import (
... UserUpdate,
... SessionCredentials,
... )
>>> from cognite.client.data_classes import ClientCredentials
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> session = client.iam.sessions.create(
... ClientCredentials(os.environ["IDP_CLIENT_ID"], os.environ["IDP_CLIENT_SECRET"]),
... session_type="CLIENT_CREDENTIALS",
... )
>>> update = UserUpdate("myUser").credentials.set(
... SessionCredentials(nonce=session.nonce)
... )
>>> res = client.postgres_gateway.users.update(update)
"""
return await self._update_multiple(
items=items,
list_cls=UserList,
resource_cls=User,
update_cls=UserUpdate,
)
async def delete(self, username: str | SequenceNotStr[str], ignore_unknown_ids: bool = False) -> None:
"""`Delete postgres user(s) <https://api-docs.cognite.com/20230101-beta/tag/Postgres-Gateway-Users/operation/delete_users>`_.
Delete postgres users
Args:
username (str | SequenceNotStr[str]): Usernames of the users to delete.
ignore_unknown_ids (bool): Ignore usernames that are not found
Examples:
Delete users:
>>> from cognite.client import CogniteClient, AsyncCogniteClient
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> client.postgres_gateway.users.delete(["myUser", "myUser2"])
"""
extra_body_fields = {"ignore_unknown_ids": ignore_unknown_ids}
await self._delete_multiple(
identifiers=UsernameSequence.load(usernames=username),
wrap_ids=True,
returns_items=False,
extra_body_fields=extra_body_fields,
)
@overload
async def retrieve(self, username: str, ignore_unknown_ids: bool = False) -> User: ...
@overload
async def retrieve(self, username: SequenceNotStr[str], ignore_unknown_ids: bool = False) -> UserList: ...
async def retrieve(self, username: str | SequenceNotStr[str], ignore_unknown_ids: bool = False) -> User | UserList:
"""`Retrieve a list of users by their usernames <https://api-docs.cognite.com/20230101-beta/tag/Postgres-Gateway-Users/operation/retreive_users>`_.
Retrieve a list of postgres users by their usernames, optionally ignoring unknown usernames
Args:
username (str | SequenceNotStr[str]): Usernames of the users to retrieve.
ignore_unknown_ids (bool): Ignore usernames that are not found
Returns:
User | UserList: The retrieved user(s).
Examples:
Retrieve user:
>>> from cognite.client import CogniteClient, AsyncCogniteClient
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> res = client.postgres_gateway.users.retrieve("myUser", ignore_unknown_ids=True)
"""
return await self._retrieve_multiple(
list_cls=UserList,
resource_cls=User,
identifiers=UsernameSequence.load(usernames=username),
ignore_unknown_ids=ignore_unknown_ids,
)
async def list(self, limit: int = DEFAULT_LIMIT_READ) -> UserList:
"""`Fetch scoped users <https://api-docs.cognite.com/20230101-beta/tag/Postgres-Gateway-Users/operation/filter_users>`_.
List all users in a given project.
Args:
limit (int): Limits the number of results to be returned.
Returns:
UserList: A list of users
Examples:
List users:
>>> from cognite.client import CogniteClient, AsyncCogniteClient
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> user_list = client.postgres_gateway.users.list(limit=5)
Iterate over users, one-by-one:
>>> for user in client.postgres_gateway.users():
... user # do something with the user
Iterate over chunks of users to reduce memory load:
>>> for user_list in client.postgres_gateway.users(chunk_size=25):
... user_list # do something with the users
"""
return await self._list(
list_cls=UserList,
resource_cls=User,
method="GET",
limit=limit,
)