stidapi 1.4.4__tar.gz → 1.5.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stidapi
3
- Version: 1.4.4
3
+ Version: 1.5.0
4
4
  Summary: Python client for connecting to Equinor STIDapi
5
5
  Author: Åsmund Våge Fannemel
6
6
  Author-email: Åsmund Våge Fannemel <asmf@equinor.com>
@@ -11,7 +11,7 @@ Classifier: Programming Language :: Python :: 3.11
11
11
  Classifier: Programming Language :: Python :: 3.12
12
12
  Classifier: Programming Language :: Python :: 3.13
13
13
  Classifier: Programming Language :: Python :: 3.14
14
- Requires-Dist: eq-api-connector>=1.1.1,<2
14
+ Requires-Dist: eq-api-connector>=1.3.0,<2
15
15
  Requires-Python: >=3.10, <4
16
16
  Project-URL: repository, https://github.com/equinor/STIDapi-python
17
17
  Description-Content-Type: text/markdown
@@ -30,18 +30,40 @@ from stidapi import Plant, Tag, Doc
30
30
 
31
31
  p = Plant("JSV")
32
32
  t = p.search_tag("*20LIC*")
33
- t2 = Tag("JSV",t[0].no)
33
+ tag_no = t[0].no
34
+ t2 = Tag("JSV", tag_no)
34
35
 
35
36
 
36
37
  d = t2.get_doc()
37
- d2 = p.get_doc(d[0].no)
38
- d3 = Doc(p.inst_code, d[0].no)
38
+ doc_no = d[0].no
39
+ d2 = p.get_doc(doc_no)
40
+ d3 = Doc(p.inst_code, doc_no)
39
41
  ```
40
42
 
41
43
  ## Installing
42
44
 
43
45
  Install package from pypi using `pip install stidapi`
44
46
 
47
+ ## Client configuration
48
+
49
+ All resource reads share one lazily initialized `STIDApiClient`. To customize
50
+ it, configure and register it before any resource reads or concurrent workers:
51
+
52
+ ```python
53
+ from stidapi import STIDApiClient, get_api_client, set_api_client
54
+
55
+ client = STIDApiClient()
56
+ set_api_client(client)
57
+ assert get_api_client() is client
58
+ ```
59
+
60
+ The existing accessors in `stidapi.utils` remain available. Registering the same
61
+ instance again is allowed, but replacing the shared client raises `RuntimeError`.
62
+ The shared client and plant cache support one identity and gateway per process;
63
+ do not change either after resource reads. Separate identities or gateways require
64
+ separate processes. Provider initialization is thread-safe, but this does not
65
+ guarantee that concurrent requests using the connector are thread-safe.
66
+
45
67
  ## Developing / testing
46
68
 
47
69
  Dependency manager uv is preferred for developers. Install with required packages for testing and coverage:
@@ -49,6 +71,10 @@ Dependency manager uv is preferred for developers. Install with required package
49
71
 
50
72
  Call `uv run pytest` to run tests.
51
73
 
74
+ Run the offline client lifecycle tests with `uv run pytest -m ci`.
75
+ The remaining legacy tests are not classified by that marker and include live
76
+ STID calls requiring authorized access; the full suite is not CI-safe.
77
+
52
78
  To generate coverage report run `uv run pytest --cov=stidapi tests/ --cov-report=xml`
53
79
 
54
80
  To compare coverage with master branch run
@@ -0,0 +1,64 @@
1
+ # STIDapi-python
2
+ A simple wrapper package to interface Equinor [STIDapi](https://stidapi.equinor.com/) using python and get plant, system, tag and doc data.
3
+
4
+
5
+ ## Use
6
+
7
+ Try it out by running the [demo](examples/demo.py) or the sample code below.
8
+
9
+ ```
10
+ from stidapi import Plant, Tag, Doc
11
+
12
+
13
+ p = Plant("JSV")
14
+ t = p.search_tag("*20LIC*")
15
+ tag_no = t[0].no
16
+ t2 = Tag("JSV", tag_no)
17
+
18
+
19
+ d = t2.get_doc()
20
+ doc_no = d[0].no
21
+ d2 = p.get_doc(doc_no)
22
+ d3 = Doc(p.inst_code, doc_no)
23
+ ```
24
+
25
+ ## Installing
26
+
27
+ Install package from pypi using `pip install stidapi`
28
+
29
+ ## Client configuration
30
+
31
+ All resource reads share one lazily initialized `STIDApiClient`. To customize
32
+ it, configure and register it before any resource reads or concurrent workers:
33
+
34
+ ```python
35
+ from stidapi import STIDApiClient, get_api_client, set_api_client
36
+
37
+ client = STIDApiClient()
38
+ set_api_client(client)
39
+ assert get_api_client() is client
40
+ ```
41
+
42
+ The existing accessors in `stidapi.utils` remain available. Registering the same
43
+ instance again is allowed, but replacing the shared client raises `RuntimeError`.
44
+ The shared client and plant cache support one identity and gateway per process;
45
+ do not change either after resource reads. Separate identities or gateways require
46
+ separate processes. Provider initialization is thread-safe, but this does not
47
+ guarantee that concurrent requests using the connector are thread-safe.
48
+
49
+ ## Developing / testing
50
+
51
+ Dependency manager uv is preferred for developers. Install with required packages for testing and coverage:
52
+ `uv sync`
53
+
54
+ Call `uv run pytest` to run tests.
55
+
56
+ Run the offline client lifecycle tests with `uv run pytest -m ci`.
57
+ The remaining legacy tests are not classified by that marker and include live
58
+ STID calls requiring authorized access; the full suite is not CI-safe.
59
+
60
+ To generate coverage report run `uv run pytest --cov=stidapi tests/ --cov-report=xml`
61
+
62
+ To compare coverage with master branch run
63
+ `uv run diff-cover coverage.xml --compare-branch master`
64
+
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "stidapi"
3
- version = "1.4.4"
3
+ version = "1.5.0"
4
4
  description = "Python client for connecting to Equinor STIDapi"
5
5
  requires-python = ">=3.10,<4"
6
6
  readme = "README.md"
@@ -13,7 +13,7 @@ classifiers = [
13
13
  "Programming Language :: Python :: 3.13",
14
14
  "Programming Language :: Python :: 3.14",
15
15
  ]
16
- dependencies = ["eq-api-connector>=1.1.1,<2"]
16
+ dependencies = ["eq-api-connector>=1.3.0,<2"]
17
17
 
18
18
  [[project.authors]]
19
19
  name = "Åsmund Våge Fannemel"
@@ -31,5 +31,8 @@ dev = [
31
31
  ]
32
32
 
33
33
  [build-system]
34
- requires = ["uv_build>=0.11.16,<0.13.0"]
34
+ requires = ["uv_build>=0.11.16,<0.14.0"]
35
35
  build-backend = "uv_build"
36
+
37
+ [tool.pytest.ini_options]
38
+ markers = ["ci: offline tests without credentials or network access"]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "stidapi"
3
- version = "1.4.4"
3
+ version = "1.5.0"
4
4
  description = "Python client for connecting to Equinor STIDapi"
5
5
  authors = [{ name = "Åsmund Våge Fannemel", email = "asmf@equinor.com" }]
6
6
  requires-python = ">=3.10,<4"
@@ -14,7 +14,7 @@ classifiers = [
14
14
  "Programming Language :: Python :: 3.13",
15
15
  "Programming Language :: Python :: 3.14",
16
16
  ]
17
- dependencies = ["eq-api-connector>=1.1.1,<2"]
17
+ dependencies = ["eq-api-connector>=1.3.0,<2"]
18
18
 
19
19
  [project.urls]
20
20
  repository = "https://github.com/equinor/STIDapi-python"
@@ -28,5 +28,8 @@ dev = [
28
28
  ]
29
29
 
30
30
  [build-system]
31
- requires = ["uv_build>=0.11.16,<0.13.0"]
31
+ requires = ["uv_build>=0.11.16,<0.14.0"]
32
32
  build-backend = "uv_build"
33
+
34
+ [tool.pytest.ini_options]
35
+ markers = ["ci: offline tests without credentials or network access"]
@@ -0,0 +1,19 @@
1
+ import logging
2
+
3
+ from .doc import Doc
4
+ from .tag import Tag
5
+ from .plant import Plant
6
+ from .system import System
7
+ from .utils import STIDApiClient, get_api_client, set_api_client
8
+
9
+ __all__ = [
10
+ "Doc",
11
+ "Tag",
12
+ "Plant",
13
+ "System",
14
+ "STIDApiClient",
15
+ "get_api_client",
16
+ "set_api_client",
17
+ ]
18
+
19
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
@@ -220,7 +220,7 @@ class Doc:
220
220
  raise ValueError("doc_no must be a non-empty string")
221
221
 
222
222
  self._data: Dict[str, Any] = {}
223
- self._full_data_loaded = data is None or "currentRevision" in data
223
+ self._full_data_loaded = data is None or self._has_full_data(data)
224
224
 
225
225
  if data is not None:
226
226
  self._data = data
@@ -244,6 +244,15 @@ class Doc:
244
244
  """Get document number."""
245
245
  return self._data.get("docNo", "")
246
246
 
247
+ @staticmethod
248
+ def _has_full_data(data: Dict[str, Any]) -> bool:
249
+ """Return whether document data contains usable revision information."""
250
+ current_revision = data.get("currentRevision")
251
+ if isinstance(current_revision, dict) and current_revision:
252
+ return True
253
+ project_revisions = data.get("projectRevisions")
254
+ return isinstance(project_revisions, list) and bool(project_revisions)
255
+
247
256
  def _ensure_full_data(self) -> None:
248
257
  """Reload document data once when initialized from a partial reference."""
249
258
  if self._full_data_loaded:
@@ -354,10 +363,8 @@ class Doc:
354
363
  if not inst_code or not doc_no:
355
364
  return None
356
365
 
357
- url = urljoin(
358
- u.get_api_url(), str(inst_code) + "/document?docNo=" + str(doc_no)
359
- )
360
- return u.get_json(url)
366
+ url = u.build_url(f"{inst_code}/document", {"docNo": doc_no})
367
+ return u.get_json_dict(url)
361
368
 
362
369
  @staticmethod
363
370
  def from_data(data: Dict[str, Any]) -> "Doc":
@@ -91,10 +91,11 @@ class Plant:
91
91
  @classmethod
92
92
  def get_all_data(cls):
93
93
  if len(cls._plant_list) == 0:
94
- parsed_json = u.get_json("/plants")
94
+ parsed_json = u.get_json_list("/plants")
95
95
 
96
- if isinstance(parsed_json, list):
97
- cls._plant_list = [x for x in parsed_json if "instCode" in x]
96
+ cls._plant_list = [
97
+ x for x in parsed_json if isinstance(x, dict) and "instCode" in x
98
+ ]
98
99
 
99
100
  return cls._plant_list
100
101
 
@@ -1,6 +1,4 @@
1
1
  from typing import Any, Dict, List, Optional
2
- from urllib.parse import urljoin
3
-
4
2
  import stidapi.utils as u
5
3
 
6
4
 
@@ -50,9 +48,8 @@ class System:
50
48
  Returns:
51
49
  List of dictionaries containing system data.
52
50
  """
53
- url = urljoin(u.get_api_url(), f"{inst_code}/system?isValid={is_valid}")
54
- parsed_json = u.get_json(url)
55
- return parsed_json if isinstance(parsed_json, list) else []
51
+ url = u.build_url(f"{inst_code}/system", {"isValid": is_valid})
52
+ return [item for item in u.get_json_list(url) if isinstance(item, dict)]
56
53
 
57
54
  @staticmethod
58
55
  def get_system(inst_code: str, get_statistics: bool = False) -> List["System"]:
@@ -1,6 +1,4 @@
1
1
  from typing import Any, Dict, List, Optional, Tuple, Union
2
- from urllib.parse import urljoin
3
-
4
2
  from stidapi import Doc
5
3
  import stidapi.utils as u
6
4
 
@@ -41,28 +39,6 @@ class Tag:
41
39
  else:
42
40
  self._data = data
43
41
 
44
- if self.is_function:
45
- function_prop = [("functionBlock", "FB")]
46
- for prop in function_prop:
47
- if prop[0] in self._data:
48
- self.__setattr__(prop[1], self._data[prop[0]])
49
-
50
- if self.is_signal:
51
- signal_prop = [("signalType", "signalType")]
52
- for prop in signal_prop:
53
- if prop[0] in self._data:
54
- self.__setattr__(prop[1], self._data[prop[0]])
55
-
56
- optional_prop = [
57
- ("setpointL", "L"),
58
- ("setpointLl", "LL"),
59
- ("setpointH", "H"),
60
- ("setpointHh", "HH"),
61
- ]
62
- for prop in optional_prop:
63
- if prop[0] in self._data and self._data[prop[0]] is not None:
64
- self.__setattr__(prop[1], self._data[prop[0]])
65
-
66
42
  @property
67
43
  def data(self) -> Dict[str, Any]:
68
44
  """Get the tag data dictionary."""
@@ -107,15 +83,67 @@ class Tag:
107
83
 
108
84
  @property
109
85
  def is_function(self) -> bool:
110
- """Check if tag is a function block."""
111
- return bool(
112
- self.data.get("isFunction", self.category_description == "FUNCTION")
86
+ """Check if tag is a function tag.
87
+
88
+ True when the tag category is FUNCTION or when STID flags the tag as
89
+ having function data (``isFunction``).
90
+ """
91
+ return self.category_description == "FUNCTION" or bool(
92
+ self.data.get("isFunction", False)
113
93
  )
114
94
 
115
95
  @property
116
96
  def is_signal(self) -> bool:
117
- """Check if tag is a signal."""
118
- return bool(self.data.get("isSignal", self.category_description == "SIGNAL"))
97
+ """Check if tag is a signal tag.
98
+
99
+ True when the tag category is SIGNAL or when STID flags the tag as
100
+ having signal data (``isSignal``).
101
+ """
102
+ return self.category_description == "SIGNAL" or bool(
103
+ self.data.get("isSignal", False)
104
+ )
105
+
106
+ @property
107
+ def FB(self) -> Optional[str]:
108
+ """Get the function-block code for function tags.
109
+
110
+ Returns "" for tags identified by is_function without a defined function
111
+ block and None for tags that are not identified as functions.
112
+ """
113
+ if not self.is_function:
114
+ return None
115
+ return str(self.data.get("functionBlock") or "")
116
+
117
+ @property
118
+ def signalType(self) -> Optional[str]:
119
+ """Get the signal type for signal tags.
120
+
121
+ Returns "" for tags identified by is_signal without a defined signal
122
+ type and None for tags that are not identified as signals.
123
+ """
124
+ if not self.is_signal:
125
+ return None
126
+ return str(self.data.get("signalType") or "")
127
+
128
+ @property
129
+ def L(self) -> Optional[str]:
130
+ """Get the low setpoint, if defined."""
131
+ return self.data.get("setpointL")
132
+
133
+ @property
134
+ def LL(self) -> Optional[str]:
135
+ """Get the low-low setpoint, if defined."""
136
+ return self.data.get("setpointLl")
137
+
138
+ @property
139
+ def H(self) -> Optional[str]:
140
+ """Get the high setpoint, if defined."""
141
+ return self.data.get("setpointH")
142
+
143
+ @property
144
+ def HH(self) -> Optional[str]:
145
+ """Get the high-high setpoint, if defined."""
146
+ return self.data.get("setpointHh")
119
147
 
120
148
  @property
121
149
  def status(self) -> str:
@@ -190,12 +218,11 @@ class Tag:
190
218
  Returns:
191
219
  List[dict]: List of dicts describing document references.
192
220
  """
193
- url = urljoin(
194
- u.get_api_url(),
195
- f"{str(self.inst_code)}/tag/document-refs?tagNo={str(self.tag_no)}&noContentAs200=true",
221
+ url = u.build_url(
222
+ f"{self.inst_code}/tag/document-refs",
223
+ {"tagNo": self.tag_no, "noContentAs200": True},
196
224
  )
197
- json_data = u.get_json(url)
198
- return json_data if isinstance(json_data, list) else []
225
+ return [item for item in u.get_json_list(url) if isinstance(item, dict)]
199
226
 
200
227
  def get_functional_location(self) -> str:
201
228
  """Get functional location of Tagged item or empty string if it does not have a functional location.
@@ -203,11 +230,10 @@ class Tag:
203
230
  Returns:
204
231
  str: Functional location or empty string if tagged item does not have a functional location.
205
232
  """
206
- url = urljoin(
207
- u.get_api_url(),
208
- f"portal/{self.inst_code}/tag/sap-tag?tagNo={self.tag_no}",
233
+ url = u.build_url(
234
+ f"portal/{self.inst_code}/tag/sap-tag", {"tagNo": self.tag_no}
209
235
  )
210
- json_data = u.get_json(url)
236
+ json_data = u.get_json_dict(url)
211
237
 
212
238
  if isinstance(json_data, dict) and "functionalLocation" in json_data:
213
239
  return json_data.get("functionalLocation", "")
@@ -237,7 +263,7 @@ class Tag:
237
263
  if not inst_code or not tag_no:
238
264
  return {}
239
265
 
240
- url = urljoin(u.get_api_url(), str(inst_code) + "/tag?tagNo=" + str(tag_no))
266
+ url = u.build_url(f"{inst_code}/tag", {"tagNo": tag_no})
241
267
  data = u.get_json(url)
242
268
 
243
269
  if isinstance(data, list) and len(data) == 1:
@@ -279,53 +305,20 @@ class Tag:
279
305
  List[Tag]: List of Tag objects with a bit less data than when getting
280
306
  """
281
307
 
282
- # Build query parameters
283
- if len(tag_no) > 0:
284
- tag_no = "tagNo=" + tag_no + "&"
285
-
286
- if len(description) > 0:
287
- description = "description=" + description + "&"
288
-
289
- if len(tag_status) > 0:
290
- tag_status = "tagStatus=" + tag_status + "&"
291
-
292
- if tag_category > 0:
293
- tag_category_string = "tagCategory=" + str(tag_category) + "&"
294
- else:
295
- tag_category_string = ""
296
-
297
- if len(tag_type) > 0:
298
- tag_type = "tagType=" + tag_type + "&"
299
-
300
- if len(system) > 0:
301
- system = "system=" + system + "&"
302
-
303
- if len(discipline_code) > 0:
304
- discipline_code = "disciplineCode=" + discipline_code + "&"
305
-
306
- skip_string = "skip=" + str(skip) + "&"
307
-
308
- # take shall be last, thus no trailing &
309
- take_string = "take=" + str(take)
310
-
311
- url = urljoin(
312
- u.get_api_url(),
313
- f"/{inst_code}/tags"
314
- + "?"
315
- + str(tag_no)
316
- + str(description)
317
- + str(tag_status)
318
- + str(tag_category_string)
319
- + str(tag_type)
320
- + str(system)
321
- + str(skip_string)
322
- + str(take_string),
323
- )
324
-
325
- result = u.get_json(url)
326
- if isinstance(result, list):
327
- return [Tag(data=x) for x in result]
328
- return []
308
+ query = {
309
+ "tagNo": tag_no,
310
+ "description": description,
311
+ "tagStatus": tag_status,
312
+ "tagCategory": tag_category if tag_category > 0 else None,
313
+ "tagType": tag_type,
314
+ "system": system,
315
+ "disciplineCode": discipline_code,
316
+ "skip": skip,
317
+ "take": take,
318
+ }
319
+ url = u.build_url(f"{inst_code}/tags", query)
320
+
321
+ return [Tag(data=x) for x in u.get_json_list(url) if isinstance(x, dict)]
329
322
 
330
323
  @staticmethod
331
324
  def search_additional_field(
@@ -341,17 +334,17 @@ class Tag:
341
334
  Returns:
342
335
  List[Tag]: List of Tag objects
343
336
  """
344
- url = urljoin(
345
- u.get_api_url(),
346
- f"/{inst_code}/tag-additional-field/{field_name}?searchValue={value}&noContentAs200=true",
337
+ url = u.build_url(
338
+ f"{inst_code}/tag-additional-field/{field_name}",
339
+ {"searchValue": value, "noContentAs200": True},
347
340
  )
348
- res = u.get_json(url)
349
-
350
- if isinstance(res, list):
351
- return [Tag(inst_code=inst_code, tag_no=x["tagNo"], data=x) for x in res]
352
- return []
341
+ res = u.get_json_list(url)
353
342
 
354
- raise ValueError(f"Invalid data {res} returned from query {url}")
343
+ return [
344
+ Tag(inst_code=inst_code, tag_no=x["tagNo"], data=x)
345
+ for x in res
346
+ if isinstance(x, dict) and "tagNo" in x
347
+ ]
355
348
 
356
349
  @staticmethod
357
350
  def get_from_additional_field(
@@ -359,6 +352,7 @@ class Tag:
359
352
  value: str = "",
360
353
  inst_code: Optional[Union[str, List[str]]] = None,
361
354
  stop_first: bool = True,
355
+ max_workers: int = 4,
362
356
  ) -> List["Tag"]:
363
357
  """Get List of Tag objects by searching for additional fields
364
358
 
@@ -368,7 +362,8 @@ class Tag:
368
362
  inst_code: STID plant code, or list of codes, to limit search to.
369
363
  Defaults to empty which will search all.
370
364
  stop_first (boolean): Set to False to get matches from all provided inst_code,
371
- else will stop at first match. Defaults to False.
365
+ else will stop at the first matching installation. Defaults to True.
366
+ max_workers (int): Maximum concurrent installation searches. Defaults to 4.
372
367
 
373
368
  Returns:
374
369
  List[Tag): List of Tag objects
@@ -382,18 +377,34 @@ class Tag:
382
377
  if isinstance(inst_code, str):
383
378
  inst_code = [inst_code]
384
379
 
380
+ if max_workers < 1:
381
+ raise ValueError("max_workers must be at least 1")
382
+
383
+ inst_codes = list(inst_code)
385
384
  res = []
386
- for code in inst_code:
387
- try:
388
- res_code = Tag.search_additional_field(
389
- inst_code=code, field_name=field_name, value=value
385
+ for start in range(0, len(inst_codes), max_workers):
386
+ codes = inst_codes[start : start + max_workers]
387
+ urls = [
388
+ u.build_url(
389
+ f"{code}/tag-additional-field/{field_name}",
390
+ {"searchValue": value, "noContentAs200": True},
390
391
  )
392
+ for code in codes
393
+ ]
394
+ try:
395
+ responses = u.get_json_lists(urls, max_workers=max_workers)
391
396
  except ValueError:
392
397
  continue
393
- if len(res_code) > 0:
394
- res.extend(res_code)
395
-
396
- if stop_first:
397
- break
398
+ for code, response in zip(codes, responses):
399
+ res_code = [
400
+ Tag(inst_code=code, tag_no=item["tagNo"], data=item)
401
+ for item in response
402
+ if isinstance(item, dict) and "tagNo" in item
403
+ ]
404
+ if res_code:
405
+ res.extend(res_code)
406
+
407
+ if stop_first:
408
+ return res
398
409
 
399
410
  return res
@@ -0,0 +1,116 @@
1
+ import json
2
+ import logging
3
+ from typing import Any, Dict, List, Optional, Union
4
+ from urllib.parse import urlencode, urljoin
5
+ from eq_api_connector import APIConnector, ClientProvider
6
+ from types import SimpleNamespace
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ _scope_client = "1734406c-3449-4192-a50d-7c3a63d3f57d"
11
+
12
+
13
+ class STIDApiClient(APIConnector):
14
+ def __init__(
15
+ self,
16
+ client_secret: Optional[str] = None,
17
+ scope: Optional[Union[List[str], str]] = [
18
+ f"{_scope_client}/user_impersonation"
19
+ ],
20
+ user_name: Optional[str] = None,
21
+ user_assertion: Optional[str] = None,
22
+ ):
23
+ super().__init__(
24
+ client_id="1a35a8df-b48d-40df-987b-267968b1b198",
25
+ client_secret=client_secret,
26
+ scope=scope,
27
+ user_name=user_name,
28
+ user_assertion=user_assertion,
29
+ )
30
+ self.url_prod = "https://stidapi.equinor.com/"
31
+ # todo: set dev url
32
+
33
+
34
+ _provider = ClientProvider(STIDApiClient)
35
+
36
+
37
+ def get_api_client() -> STIDApiClient:
38
+ """Return the shared client, creating it lazily on first use."""
39
+ return _provider.get()
40
+
41
+
42
+ def set_api_client(client: STIDApiClient) -> None:
43
+ """Register a configured client before resource reads or starting workers.
44
+
45
+ The same instance may be registered again. A different client cannot replace
46
+ the registered or lazily initialized client because resource data is cached.
47
+ Do not change its identity or gateway after resource reads.
48
+
49
+ Raises:
50
+ TypeError: If client is not an STIDApiClient.
51
+ RuntimeError: If a different client is already registered or initialized.
52
+ """
53
+ _provider.set(client)
54
+
55
+
56
+ def get_api_url() -> str:
57
+ return get_api_client().url
58
+
59
+
60
+ def build_url(path: str, query: Optional[Dict[str, Any]] = None) -> str:
61
+ """Build an API URL with URL-encoded query parameters."""
62
+ url = urljoin(get_api_url(), path.lstrip("/"))
63
+ if query:
64
+ query = {
65
+ key: value
66
+ for key, value in query.items()
67
+ if value is not None and value != ""
68
+ }
69
+ if query:
70
+ url = f"{url}?{urlencode(query)}"
71
+ return url
72
+
73
+
74
+ def get_object_from_json(text: str):
75
+ if isinstance(text, list):
76
+ obj = [json.loads(x, object_hook=lambda d: SimpleNamespace(**d)) for x in text]
77
+ else:
78
+ obj = json.loads(text, object_hook=lambda d: SimpleNamespace(**d))
79
+ return obj
80
+
81
+
82
+ def get_json(url: str, raise_for_status: bool = False) -> Any:
83
+ """Fetch JSON and propagate connector errors."""
84
+ c = get_api_client()
85
+ c.raise_for_status = raise_for_status
86
+
87
+ return c.get_json(url=url)
88
+
89
+
90
+ def get_json_dict(url: str, raise_for_status: bool = False) -> Optional[Dict[str, Any]]:
91
+ """Fetch JSON and return an object, or None for another response shape."""
92
+ data = get_json(url, raise_for_status=raise_for_status)
93
+ if data is None:
94
+ return None
95
+ return data if isinstance(data, dict) else None
96
+
97
+
98
+ def get_json_list(url: str, raise_for_status: bool = False) -> List[Any]:
99
+ """Fetch JSON and return an array, or an empty list for another shape."""
100
+ data = get_json(url, raise_for_status=raise_for_status)
101
+ if data is None:
102
+ return []
103
+ return data if isinstance(data, list) else []
104
+
105
+
106
+ def get_json_lists(
107
+ urls: List[str], raise_for_status: bool = False, max_workers: int = 4
108
+ ) -> List[List[Any]]:
109
+ """Fetch JSON arrays concurrently, preserving URL order."""
110
+ if not urls:
111
+ return []
112
+
113
+ client = get_api_client()
114
+ client.raise_for_status = raise_for_status
115
+ data = client.get_multiple_json(urls, max_workers=max_workers)
116
+ return [response if isinstance(response, list) else [] for response in data]
stidapi-1.4.4/README.md DELETED
@@ -1,38 +0,0 @@
1
- # STIDapi-python
2
- A simple wrapper package to interface Equinor [STIDapi](https://stidapi.equinor.com/) using python and get plant, system, tag and doc data.
3
-
4
-
5
- ## Use
6
-
7
- Try it out by running the [demo](examples/demo.py) or the sample code below.
8
-
9
- ```
10
- from stidapi import Plant, Tag, Doc
11
-
12
-
13
- p = Plant("JSV")
14
- t = p.search_tag("*20LIC*")
15
- t2 = Tag("JSV",t[0].no)
16
-
17
-
18
- d = t2.get_doc()
19
- d2 = p.get_doc(d[0].no)
20
- d3 = Doc(p.inst_code, d[0].no)
21
- ```
22
-
23
- ## Installing
24
-
25
- Install package from pypi using `pip install stidapi`
26
-
27
- ## Developing / testing
28
-
29
- Dependency manager uv is preferred for developers. Install with required packages for testing and coverage:
30
- `uv sync`
31
-
32
- Call `uv run pytest` to run tests.
33
-
34
- To generate coverage report run `uv run pytest --cov=stidapi tests/ --cov-report=xml`
35
-
36
- To compare coverage with master branch run
37
- `uv run diff-cover coverage.xml --compare-branch master`
38
-
@@ -1,10 +0,0 @@
1
- import logging
2
-
3
- from .doc import Doc
4
- from .tag import Tag
5
- from .plant import Plant
6
- from .system import System
7
-
8
- __all__ = ["Doc", "Tag", "Plant", "System"]
9
-
10
- logging.getLogger(__name__).addHandler(logging.NullHandler())
@@ -1,66 +0,0 @@
1
- import json
2
- import logging
3
- from typing import List, Optional, Union
4
- from eq_api_connector import APIConnector
5
- from types import SimpleNamespace
6
-
7
- logger = logging.getLogger(__name__)
8
-
9
- _client = None
10
-
11
- _scope_client = "1734406c-3449-4192-a50d-7c3a63d3f57d"
12
-
13
-
14
- class STIDApiClient(APIConnector):
15
- def __init__(
16
- self,
17
- client_secret: Optional[str] = None,
18
- scope: Optional[Union[List[str], str]] = [
19
- f"{_scope_client}/user_impersonation"
20
- ],
21
- user_name: Optional[str] = None,
22
- user_assertion: Optional[str] = None,
23
- ):
24
- super().__init__(
25
- client_id="1a35a8df-b48d-40df-987b-267968b1b198",
26
- client_secret=client_secret,
27
- scope=scope,
28
- user_name=user_name,
29
- user_assertion=user_assertion,
30
- )
31
- self.url_prod = "https://stidapi.equinor.com/"
32
- # todo: set dev url
33
-
34
-
35
- def get_api_client() -> STIDApiClient:
36
- global _client
37
- if _client is None:
38
- client = STIDApiClient()
39
- set_api_client(client)
40
- return client
41
-
42
- return _client
43
-
44
-
45
- def set_api_client(client: STIDApiClient):
46
- global _client
47
- _client = client
48
-
49
-
50
- def get_api_url():
51
- return get_api_client().url
52
-
53
-
54
- def get_object_from_json(text: str):
55
- if isinstance(text, list):
56
- obj = [json.loads(x, object_hook=lambda d: SimpleNamespace(**d)) for x in text]
57
- else:
58
- obj = json.loads(text, object_hook=lambda d: SimpleNamespace(**d))
59
- return obj
60
-
61
-
62
- def get_json(url: str, raise_for_status=False):
63
- c = get_api_client()
64
- c.raise_for_status = raise_for_status
65
-
66
- return c.get_json(url=url)