Skip to content

Commit c49d2b8

Browse files
authored
chore: Split APIs "Java-style" to prepare for v8 (#2358)
1 parent d21f9e3 commit c49d2b8

37 files changed

Lines changed: 4156 additions & 3914 deletions
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
from __future__ import annotations
2+
3+
from typing import TYPE_CHECKING, overload
4+
5+
from cognite.client._api_client import APIClient
6+
from cognite.client.data_classes.data_modeling.ids import _load_space_identifier
7+
from cognite.client.data_classes.data_modeling.statistics import (
8+
SpaceStatistics,
9+
SpaceStatisticsList,
10+
)
11+
from cognite.client.utils.useful_types import SequenceNotStr
12+
13+
if TYPE_CHECKING:
14+
from cognite.client._cognite_client import CogniteClient
15+
from cognite.client.config import ClientConfig
16+
17+
18+
class SpaceStatisticsAPI(APIClient):
19+
_RESOURCE_PATH = "/models/statistics/spaces"
20+
21+
def __init__(self, config: ClientConfig, api_version: str | None, cognite_client: CogniteClient) -> None:
22+
super().__init__(config, api_version, cognite_client)
23+
self._RETRIEVE_LIMIT = 100
24+
25+
@overload
26+
def retrieve(self, space: str) -> SpaceStatistics | None: ...
27+
28+
@overload
29+
def retrieve(self, space: SequenceNotStr[str]) -> SpaceStatisticsList: ...
30+
31+
def retrieve(
32+
self,
33+
space: str | SequenceNotStr[str],
34+
) -> SpaceStatistics | SpaceStatisticsList | None:
35+
"""`Retrieve usage data and limits per space <https://developer.cognite.com/api#tag/Statistics/operation/getSpaceStatisticsByIds>`_
36+
37+
Args:
38+
space (str | SequenceNotStr[str]): The space or spaces to retrieve statistics for.
39+
40+
Returns:
41+
SpaceStatistics | SpaceStatisticsList | None: The requested statistics and limits for the specified space(s).
42+
43+
Examples:
44+
45+
Fetch statistics for a single space:
46+
47+
>>> from cognite.client import CogniteClient
48+
>>> client = CogniteClient()
49+
>>> result = client.data_modeling.statistics.spaces.retrieve("my-space")
50+
51+
Fetch statistics for multiple spaces:
52+
>>> res = client.data_modeling.statistics.spaces.retrieve(
53+
... ["my-space1", "my-space2"]
54+
... )
55+
56+
"""
57+
return self._retrieve_multiple(
58+
SpaceStatisticsList,
59+
SpaceStatistics,
60+
identifiers=_load_space_identifier(space),
61+
resource_path=self._RESOURCE_PATH,
62+
)
63+
64+
def list(self) -> SpaceStatisticsList:
65+
"""`Retrieve usage for all spaces <https://developer.cognite.com/api#tag/Statistics/operation/getSpaceStatistics>`_
66+
67+
Returns statistics for data modeling resources grouped by each space in the project.
68+
69+
Returns:
70+
SpaceStatisticsList: The requested statistics and limits for all spaces in the project.
71+
72+
Examples:
73+
74+
Fetch statistics for all spaces in the project:
75+
76+
>>> from cognite.client import CogniteClient
77+
>>> client = CogniteClient()
78+
>>> stats = client.data_modeling.statistics.spaces.list()
79+
>>> for space_stats in stats:
80+
... print(f"Space: {space_stats.space}, Nodes: {space_stats.nodes}")
81+
82+
"""
83+
# None 2xx responses are handled by the _get method.
84+
response = self._get(self._RESOURCE_PATH)
85+
return SpaceStatisticsList._load(response.json()["items"], self._cognite_client)

cognite/client/_api/data_modeling/statistics.py

Lines changed: 2 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,91 +1,18 @@
11
from __future__ import annotations
22

3-
from typing import TYPE_CHECKING, overload
3+
from typing import TYPE_CHECKING
44

5+
from cognite.client._api.data_modeling.space_statistics import SpaceStatisticsAPI
56
from cognite.client._api_client import APIClient
6-
from cognite.client.data_classes.data_modeling.ids import _load_space_identifier
77
from cognite.client.data_classes.data_modeling.statistics import (
88
ProjectStatistics,
9-
SpaceStatistics,
10-
SpaceStatisticsList,
119
)
12-
from cognite.client.utils.useful_types import SequenceNotStr
1310

1411
if TYPE_CHECKING:
1512
from cognite.client._cognite_client import CogniteClient
1613
from cognite.client.config import ClientConfig
1714

1815

19-
class SpaceStatisticsAPI(APIClient):
20-
_RESOURCE_PATH = "/models/statistics/spaces"
21-
22-
def __init__(self, config: ClientConfig, api_version: str | None, cognite_client: CogniteClient) -> None:
23-
super().__init__(config, api_version, cognite_client)
24-
self._RETRIEVE_LIMIT = 100
25-
26-
@overload
27-
def retrieve(self, space: str) -> SpaceStatistics | None: ...
28-
29-
@overload
30-
def retrieve(self, space: SequenceNotStr[str]) -> SpaceStatisticsList: ...
31-
32-
def retrieve(
33-
self,
34-
space: str | SequenceNotStr[str],
35-
) -> SpaceStatistics | SpaceStatisticsList | None:
36-
"""`Retrieve usage data and limits per space <https://developer.cognite.com/api#tag/Statistics/operation/getSpaceStatisticsByIds>`_
37-
38-
Args:
39-
space (str | SequenceNotStr[str]): The space or spaces to retrieve statistics for.
40-
41-
Returns:
42-
SpaceStatistics | SpaceStatisticsList | None: The requested statistics and limits for the specified space(s).
43-
44-
Examples:
45-
46-
Fetch statistics for a single space:
47-
48-
>>> from cognite.client import CogniteClient
49-
>>> client = CogniteClient()
50-
>>> result = client.data_modeling.statistics.spaces.retrieve("my-space")
51-
52-
Fetch statistics for multiple spaces:
53-
>>> res = client.data_modeling.statistics.spaces.retrieve(
54-
... ["my-space1", "my-space2"]
55-
... )
56-
57-
"""
58-
return self._retrieve_multiple(
59-
SpaceStatisticsList,
60-
SpaceStatistics,
61-
identifiers=_load_space_identifier(space),
62-
resource_path=self._RESOURCE_PATH,
63-
)
64-
65-
def list(self) -> SpaceStatisticsList:
66-
"""`Retrieve usage for all spaces <https://developer.cognite.com/api#tag/Statistics/operation/getSpaceStatistics>`_
67-
68-
Returns statistics for data modeling resources grouped by each space in the project.
69-
70-
Returns:
71-
SpaceStatisticsList: The requested statistics and limits for all spaces in the project.
72-
73-
Examples:
74-
75-
Fetch statistics for all spaces in the project:
76-
77-
>>> from cognite.client import CogniteClient
78-
>>> client = CogniteClient()
79-
>>> stats = client.data_modeling.statistics.spaces.list()
80-
>>> for space_stats in stats:
81-
... print(f"Space: {space_stats.space}, Nodes: {space_stats.nodes}")
82-
83-
"""
84-
# None 2xx responses are handled by the _get method.
85-
response = self._get(self._RESOURCE_PATH)
86-
return SpaceStatisticsList._load(response.json()["items"], self._cognite_client)
87-
88-
8916
class StatisticsAPI(APIClient):
9017
_RESOURCE_PATH = "/models/statistics"
9118

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
from __future__ import annotations
2+
3+
from pathlib import Path
4+
from typing import IO
5+
6+
from cognite.client._api_client import APIClient
7+
from cognite.client.data_classes.documents import (
8+
TemporaryLink,
9+
)
10+
11+
12+
class DocumentPreviewAPI(APIClient):
13+
_RESOURCE_PATH = "/documents"
14+
15+
def download_page_as_png_bytes(self, id: int, page_number: int = 1) -> bytes:
16+
"""`Downloads an image preview for a specific page of the specified document. <https://developer.cognite.com/api#tag/Document-preview/operation/documentsPreviewImagePage>`_
17+
18+
Args:
19+
id (int): The server-generated ID for the document you want to retrieve the preview of.
20+
page_number (int): Page number to preview. Starting at 1 for first page.
21+
22+
Returns:
23+
bytes: The png preview of the document.
24+
25+
Examples:
26+
27+
Download image preview of page 5 of file with id 123:
28+
29+
>>> from cognite.client import CogniteClient
30+
>>> client = CogniteClient()
31+
>>> content = client.documents.previews.download_page_as_png_bytes(id=123, page_number=5)
32+
33+
Download an image preview and display using IPython.display.Image (for example in a Jupyter Notebook):
34+
35+
>>> from IPython.display import Image
36+
>>> binary_png = client.documents.previews.download_page_as_png_bytes(id=123, page_number=5)
37+
>>> Image(binary_png)
38+
"""
39+
res = self._do_request(
40+
"GET", f"{self._RESOURCE_PATH}/{id}/preview/image/pages/{page_number}", accept="image/png"
41+
)
42+
return res.content
43+
44+
def download_page_as_png(
45+
self, path: Path | str | IO, id: int, page_number: int = 1, overwrite: bool = False
46+
) -> None:
47+
"""`Downloads an image preview for a specific page of the specified document. <https://developer.cognite.com/api#tag/Document-preview/operation/documentsPreviewImagePage>`_
48+
49+
Args:
50+
path (Path | str | IO): The path to save the png preview of the document. If the path is a directory, the file name will be '[id]_page[page_number].png'.
51+
id (int): The server-generated ID for the document you want to retrieve the preview of.
52+
page_number (int): Page number to preview. Starting at 1 for first page.
53+
overwrite (bool): Whether to overwrite existing file at the given path. Defaults to False.
54+
55+
Examples:
56+
57+
Download Image preview of page 5 of file with id 123 to folder "previews":
58+
59+
>>> from cognite.client import CogniteClient
60+
>>> client = CogniteClient()
61+
>>> client.documents.previews.download_page_as_png("previews", id=123, page_number=5)
62+
"""
63+
if isinstance(path, IO):
64+
content = self.download_page_as_png_bytes(id)
65+
path.write(content)
66+
return
67+
68+
if (path := Path(path)).is_dir():
69+
path /= f"{id}_page{page_number}.png"
70+
elif path.suffix != ".png":
71+
raise ValueError("Path must be a directory or end with .png")
72+
if not overwrite and path.exists():
73+
raise FileExistsError(f"File {path} already exists. Use overwrite=True to overwrite existing file.")
74+
content = self.download_page_as_png_bytes(id, page_number)
75+
path.write_bytes(content)
76+
77+
def download_document_as_pdf_bytes(self, id: int) -> bytes:
78+
"""`Downloads a pdf preview of the specified document. <https://developer.cognite.com/api#tag/Document-preview/operation/documentsPreviewPdf>`_
79+
80+
Previews will be rendered if necessary during the request. Be prepared for the request to take a few seconds to complete.
81+
82+
Args:
83+
id (int): The server-generated ID for the document you want to retrieve the preview of.
84+
85+
Returns:
86+
bytes: The pdf preview of the document.
87+
88+
Examples:
89+
90+
Download PDF preview of file with id 123:
91+
92+
>>> from cognite.client import CogniteClient
93+
>>> client = CogniteClient()
94+
>>> content = client.documents.previews.download_document_as_pdf_bytes(id=123)
95+
"""
96+
res = self._do_request("GET", f"{self._RESOURCE_PATH}/{id}/preview/pdf", accept="application/pdf")
97+
return res.content
98+
99+
def download_document_as_pdf(self, path: Path | str | IO, id: int, overwrite: bool = False) -> None:
100+
"""`Downloads a pdf preview of the specified document. <https://developer.cognite.com/api#tag/Document-preview/operation/documentsPreviewPdf>`_
101+
102+
Previews will be rendered if necessary during the request. Be prepared for the request to take a few seconds to complete.
103+
104+
Args:
105+
path (Path | str | IO): The path to save the pdf preview of the document. If the path is a directory, the file name will be '[id].pdf'.
106+
id (int): The server-generated ID for the document you want to retrieve the preview of.
107+
overwrite (bool): Whether to overwrite existing file at the given path. Defaults to False.
108+
109+
Examples:
110+
111+
Download PDF preview of file with id 123 to folder "previews":
112+
113+
>>> from cognite.client import CogniteClient
114+
>>> client = CogniteClient()
115+
>>> client.documents.previews.download_document_as_pdf("previews", id=123)
116+
"""
117+
if isinstance(path, IO):
118+
content = self.download_document_as_pdf_bytes(id)
119+
path.write(content)
120+
return
121+
122+
if (path := Path(path)).is_dir():
123+
path /= f"{id}.pdf"
124+
elif path.suffix != ".pdf":
125+
raise ValueError("Path must be a directory or end with .pdf")
126+
if not overwrite and path.exists():
127+
raise FileExistsError(f"File {path} already exists. Use overwrite=True to overwrite existing file.")
128+
content = self.download_document_as_pdf_bytes(id)
129+
path.write_bytes(content)
130+
131+
def retrieve_pdf_link(self, id: int) -> TemporaryLink:
132+
"""`Retrieve a Temporary link to download pdf preview <https://developer.cognite.com/api#tag/Document-preview/operation/documentsPreviewPdfTemporaryLink>`_
133+
134+
Args:
135+
id (int): The server-generated ID for the document you want to retrieve the preview of.
136+
137+
Returns:
138+
TemporaryLink: A temporary link to download the pdf preview.
139+
140+
Examples:
141+
142+
Retrieve the PDF preview download link for document with id 123:
143+
144+
>>> from cognite.client import CogniteClient
145+
>>> client = CogniteClient()
146+
>>> link = client.documents.previews.retrieve_pdf_link(id=123)
147+
"""
148+
res = self._get(f"{self._RESOURCE_PATH}/{id}/preview/pdf/temporarylink")
149+
return TemporaryLink.load(res.json())

0 commit comments

Comments
 (0)