commonlib-reader 1.0.6__tar.gz → 1.0.8__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,18 +1,18 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: commonlib-reader
3
- Version: 1.0.6
3
+ Version: 1.0.8
4
4
  Summary: Reader for Equinor commonlib api.
5
5
  License: MIT
6
6
  Author: Åsmund Våge Fannemel
7
7
  Author-email: asmf@equinor.com
8
- Requires-Python: >=3.9.2,<4.0.0
8
+ Requires-Python: >=3.10,<4.0.0
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Programming Language :: Python :: 3
11
11
  Classifier: Programming Language :: Python :: 3.10
12
12
  Classifier: Programming Language :: Python :: 3.11
13
13
  Classifier: Programming Language :: Python :: 3.12
14
14
  Classifier: Programming Language :: Python :: 3.13
15
- Requires-Dist: msal_bearer (>=1.3.3,<2.0.0)
15
+ Requires-Dist: eq-api-connector (>=1.0.0,<2.0.0)
16
16
  Requires-Dist: pandas (>=2.1.4)
17
17
  Requires-Dist: requests (>=2.32.4)
18
18
  Requires-Dist: urllib3 (>=2.5.0)
@@ -0,0 +1,29 @@
1
+ from eq_api_connector import APIConnector
2
+
3
+ _connector = None
4
+
5
+
6
+ def get_connector() -> APIConnector:
7
+ """Get a singleton instance of the APIConnector.
8
+
9
+ Returns:
10
+ APIConnector: An instance of the APIConnector class.
11
+ """
12
+ global _connector
13
+ if _connector is None:
14
+ clientID = "728cfddd-b8e9-4ed7-b9a3-8f2fd5b8e79a"
15
+ scopes = ["37d598fc-da0f-46bd-949f-7107918d47a5/user_impersonation"]
16
+ _connector = APIConnector(client_id=clientID, scope=scopes)
17
+ _connector.set_url_prod("https://commonlibapi.equinor.com/")
18
+
19
+ return _connector
20
+
21
+
22
+ def set_connector(connector: APIConnector):
23
+ """Set the singleton instance of the APIConnector.
24
+
25
+ Args:
26
+ connector (APIConnector): An instance of the APIConnector class.
27
+ """
28
+ global _connector
29
+ _connector = connector
@@ -15,6 +15,7 @@ class Facility:
15
15
  Field (str) : Field identifier associated with the facility (if available).
16
16
  ParentFacility (str) : Parent facility identifier (if available).
17
17
  NPDID (str) : NPD ID (if available).
18
+ GovernmentalName (str) : Governmental facility name (if available).
18
19
 
19
20
  _cache (list of dict, optional):
20
21
  Class level cache to store facility data, to minimize data source access.
@@ -41,14 +42,23 @@ class Facility:
41
42
  self.name = self._data["name"]
42
43
  self.description = self._data["description"]
43
44
 
44
- common_attributes = ["SAPPlant", "Field", "ParentFacility", "NPDID"]
45
- for attr in common_attributes:
46
- self.__setattr__(attr, "")
45
+ self.SAPPlant = ""
46
+ self.Field = ""
47
+ self.ParentFacility = ""
48
+ self.NPDID = ""
49
+ self.GovernmentalName = ""
47
50
 
48
51
  for key, val in self._attributes.items():
49
- if key in common_attributes:
52
+ if key in self.__getattribute__("__dict__").keys():
50
53
  self.__setattr__(key, val)
51
54
 
55
+ self.STID = self.identity # Alias for identity
56
+ self.instCode = self.identity # Alias for identity
57
+ try:
58
+ self.SAP = int(self.SAPPlant) # Alias for SAPPlant as integer
59
+ except (TypeError, ValueError):
60
+ pass
61
+
52
62
  def isSTID(self):
53
63
  """
54
64
  Checks if the facility is marked for STID.
@@ -62,6 +72,9 @@ class Facility:
62
72
 
63
73
  return False
64
74
 
75
+ def __str__(self):
76
+ return f"Facility: {self.identity}, Name: {self.name}, Description: {self.description}"
77
+
65
78
  @classmethod
66
79
  def get_all_facilities(cls) -> List["Facility"]:
67
80
  """
@@ -92,7 +105,7 @@ class Facility:
92
105
  Retrieves the facility data for the given code.
93
106
 
94
107
  Parameters:
95
- code (str): The STID plant code corresponding to the facility.
108
+ code (str): The STID plant code corresponding to the facility. NB! SAP codes and governmental facility names can also be used.
96
109
 
97
110
  Returns:
98
111
  dict: A dictionary containing data related to the facility.
@@ -1,4 +1,5 @@
1
1
  from typing import List, Union
2
+ from commonlib_reader.facility import Facility
2
3
  from commonlib_reader.utils import attributes_list_to_dict, get_code
3
4
 
4
5
 
@@ -23,7 +24,7 @@ class IMS:
23
24
  Raises:
24
25
  ValueError: If input data is not a dict.
25
26
  """
26
- if isinstance(data, str):
27
+ if isinstance(data, str) or isinstance(data, int):
27
28
  data = IMS.from_facility(data)._data
28
29
 
29
30
  if not isinstance(data, dict):
@@ -42,11 +43,11 @@ class IMS:
42
43
  self.__setattr__(attr["definitionName"], attr["displayValue"])
43
44
 
44
45
  @staticmethod
45
- def from_facility(facility: str) -> "IMS":
46
+ def from_facility(facility: Union[Facility, str, int]) -> "IMS":
46
47
  """Get IMS instance from STID code.
47
48
 
48
49
  Args:
49
- facility (str): Facility code
50
+ facility (str): Facility inst code (STID) or SAP code.
50
51
 
51
52
  Raises:
52
53
  ValueError: Not able to instantiate IMS object from input facility code.
@@ -54,10 +55,15 @@ class IMS:
54
55
  Returns:
55
56
  IMS: IMS instance
56
57
  """
57
- if facility is None or len(facility) == 0:
58
- raise ValueError(
59
- "Facility must be provided. Empty strings are not allowed."
60
- )
58
+ if isinstance(facility, int):
59
+ facility = Facility(facility).identity
60
+
61
+ if isinstance(facility, Facility):
62
+ facility = facility.identity
63
+
64
+ if not isinstance(facility, str) or len(facility) == 0:
65
+ raise ValueError("Not able to detect facility from input {facility}.")
66
+
61
67
  ims = IMS.get_ims_list(facility=facility)
62
68
  if len(ims) == 1:
63
69
  return ims[0]
@@ -3,12 +3,12 @@ from typing import Dict, List, Optional
3
3
  from urllib.parse import urljoin
4
4
 
5
5
  import requests
6
- from msal_bearer import BearerAuth, get_user_name
6
+
7
+ from commonlib_reader.connector import get_connector
7
8
 
8
9
 
9
10
  def get_library_names():
10
- url = urljoin(get_api_url(), "api/Library/NameList")
11
- library_names = get_json(url=url)
11
+ library_names = get_connector().get_json(url="/api/Library/NameList")
12
12
  library_names.sort()
13
13
  return library_names
14
14
 
@@ -31,67 +31,13 @@ def get_code_param(code, params=None):
31
31
  if params is None:
32
32
  params = {}
33
33
 
34
- url = urljoin(get_api_url(), f"api/Code/{code}")
35
- return get_json(url, params=params)
34
+ return get_connector().get_json(f"/api/Code/{code}", params=params)
36
35
 
37
36
 
38
37
  def query_sql(sql: str):
39
38
  return post_sql(sql=sql, take=0, skip=0)
40
39
 
41
40
 
42
- def get_api_url() -> str:
43
- """Get base url to api
44
-
45
- Returns:
46
- str: Base url to api
47
- """
48
- return "https://commonlibapi.equinor.com/"
49
-
50
-
51
- def get_auth() -> BearerAuth:
52
- """Get Bearerauth object including token for accessing api.
53
-
54
- Returns:
55
- BearerAuth: Object with access token for api.
56
- """
57
- tenantID = "3aa4a235-b6e2-48d5-9195-7fcf05b459b0"
58
- clientID = "728cfddd-b8e9-4ed7-b9a3-8f2fd5b8e79a"
59
- scopes = ["37d598fc-da0f-46bd-949f-7107918d47a5/user_impersonation"]
60
- auth = BearerAuth.get_auth(
61
- tenantID=tenantID,
62
- clientID=clientID,
63
- scopes=scopes,
64
- username=f"{get_user_name()}@equinor.com",
65
- )
66
-
67
- return auth
68
-
69
-
70
- def get_json(url: str, params=None) -> list:
71
- """Get json from api endpoint
72
-
73
- Args:
74
- url (str): Url to api endpoint to get.
75
- params (dict, optional): Dictionary of parameters to pass. Defaults to None.
76
-
77
- Returns:
78
- list: List of response from api
79
- """
80
- response = requests.get(url, auth=get_auth(), params=params)
81
- # response.raise_for_status()
82
- if response.status_code == 200:
83
- try:
84
- return response.json()
85
- except json.JSONDecodeError:
86
- print(
87
- f"Warning: {str(url)} returned successfully, but not with a valid json response"
88
- )
89
- else:
90
- print(f"Warning: {str(url)} returned status code {response.status_code}")
91
-
92
- return []
93
-
94
-
95
41
  def post_sql(sql: str, take: int = 100, skip: int = 0) -> list:
96
42
  """Get json from api/sql endpoint accepting sql queries.
97
43
 
@@ -103,9 +49,12 @@ def post_sql(sql: str, take: int = 100, skip: int = 0) -> list:
103
49
  Returns:
104
50
  list: List of response from api
105
51
  """
106
- url = urljoin(get_api_url(), "api/sql")
52
+
53
+ url = urljoin(get_connector().get_url(), "api/sql")
107
54
  response = requests.post(
108
- url=url, json={"query": sql, "take": take, "skip": skip}, auth=get_auth()
55
+ url=url,
56
+ json={"query": sql, "take": take, "skip": skip},
57
+ headers={"Authorization": "Bearer " + get_connector().get_token()},
109
58
  )
110
59
  if response.status_code == 200:
111
60
  try:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "commonlib-reader"
3
- version = "1.0.6"
3
+ version = "1.0.8"
4
4
  description = "Reader for Equinor commonlib api."
5
5
  authors = [
6
6
  { name = "Åsmund Våge Fannemel", email = "asmf@equinor.com" }
@@ -8,12 +8,12 @@ authors = [
8
8
  readme = "README.md"
9
9
  license = { text = "MIT" }
10
10
  urls = {"Repository" = "https://github.com/equinor/commonlib-reader.git"}
11
- requires-python = ">=3.9.2,<4.0.0"
11
+ requires-python = ">=3.10,<4.0.0"
12
12
  dependencies = [
13
- "msal_bearer>=1.3.3,<2.0.0",
14
13
  "pandas>=2.1.4",
15
14
  "requests>=2.32.4",
16
- "urllib3>=2.5.0" # Pinned to avoid security issues in some older versions
15
+ "urllib3>=2.5.0", # Pinned to avoid security issues in some older versions
16
+ "eq-api-connector (>=1.0.0,<2.0.0)"
17
17
  ]
18
18
 
19
19
  [tool.poetry.group.test.dependencies]