Commit 555880c6 authored by Marc-Andre Santune's avatar Marc-Andre Santune
Browse files

add settings

parent 9ed41e65
from MaxIcsRegistry import MaxIcsRegistry
registry = MaxIcsRegistry.from_env(staging=False)
from .building_generic import BuildingGeneric, VersionConflictError from .building_generic import BuildingGeneric, VersionConflictError
\ No newline at end of file
...@@ -8,9 +8,7 @@ from requests.exceptions import HTTPError ...@@ -8,9 +8,7 @@ from requests.exceptions import HTTPError
from retrying import retry from retrying import retry
from simplejson import JSONDecodeError from simplejson import JSONDecodeError
from . import registry from .settings import Settings
building_center_info = registry.get_info("building-knowledge-information-center")
MAX_RETRIES = 5 # max retries number MAX_RETRIES = 5 # max retries number
WAIT_BETWEEN_RETRIES_IN_MS = 200 # time between each retry WAIT_BETWEEN_RETRIES_IN_MS = 200 # time between each retry
...@@ -23,15 +21,10 @@ class BuildingGeneric: ...@@ -23,15 +21,10 @@ class BuildingGeneric:
"""Stores the methods used to receive or update the building info from ES doc""" """Stores the methods used to receive or update the building info from ES doc"""
api_key = building_center_info["api_in"][registry.node_id]["key"] def __init__(self, uid: str, staging: str) -> None:
_base_url = "http://{}:{}/api/buildings/".format(
building_center_info["service_addr"], building_center_info["service_port"]
)
def __init__(self, uid: str) -> None:
self.logger = logging.getLogger(self.__class__.__name__) self.logger = logging.getLogger(self.__class__.__name__)
self._uid = uid self._uid = uid
self.settings = Settings(staging=staging)
self.fetch() self.fetch()
def __getitem__(self, item): def __getitem__(self, item):
...@@ -40,14 +33,14 @@ class BuildingGeneric: ...@@ -40,14 +33,14 @@ class BuildingGeneric:
# ----------------- Building level --------------------- # ----------------- Building level ---------------------
def fetch(self) -> None: def fetch(self) -> None:
"""Fetch the building document""" """Fetch the building document"""
self._building = self._req_with_retries("get", join(self._base_url, self._uid)) self._building = self._req_with_retries("get", join(self.settings.base_url, self._uid))
def update_building(self, payload) -> None: def update_building(self, payload) -> None:
""" """
Update ES doc with information at building level Update ES doc with information at building level
Note: the retries for conflict error are managed within BKC API Note: the retries for conflict error are managed within BKC API
""" """
self._req("put", join(self._base_url, self._uid), json=payload) self._req("put", join(self.settings.base_url, self._uid), json=payload)
def update_status_history(self, status: str) -> None: def update_status_history(self, status: str) -> None:
""" """
...@@ -57,25 +50,7 @@ class BuildingGeneric: ...@@ -57,25 +50,7 @@ class BuildingGeneric:
payload = { payload = {
"operation_history": [*self._building.get("operation_history"), status] "operation_history": [*self._building.get("operation_history"), status]
} }
self._req("put", join(self._base_url, self._uid), json={**payload}) self._req("put", join(self.settings.base_url, self._uid), json={**payload})
@classmethod
def by_facade_inference_id(cls, inf_id: str):
"""Retrieve a building from a facade inference id"""
building = cls._req_with_retries(
"get", join(cls._base_url, "inference/facade/", inf_id)
)
return cls(uid=building["id"])
@classmethod
def by_roof_inference_id(cls, inf_id: str):
"""Retrieve a building from a roof inference id"""
building = cls._req_with_retries(
"get", join(cls._base_url, "inference/roof/", inf_id)
)
return cls(uid=building["id"])
def register_error_for_building(self, error_code: str): def register_error_for_building(self, error_code: str):
""" """
...@@ -83,7 +58,7 @@ class BuildingGeneric: ...@@ -83,7 +58,7 @@ class BuildingGeneric:
Note: the retries for conflict error are managed within BKC API Note: the retries for conflict error are managed within BKC API
""" """
url = join(self._base_url, self._uid, "errors") url = join(self.settings.base_url, self._uid, "errors")
payload = {"error_code": error_code} payload = {"error_code": error_code}
return self._req(method="put", url=url, json=payload) return self._req(method="put", url=url, json=payload)
...@@ -92,7 +67,7 @@ class BuildingGeneric: ...@@ -92,7 +67,7 @@ class BuildingGeneric:
"""Get roof image""" """Get roof image"""
image = self._req_with_retries( image = self._req_with_retries(
"get", join(self._base_url, self._uid, "roof", "image", image_name) "get", join(self.settings.base_url, self._uid, "roof", "image", image_name)
) )
return image["image"] return image["image"]
...@@ -102,7 +77,7 @@ class BuildingGeneric: ...@@ -102,7 +77,7 @@ class BuildingGeneric:
body = {"image": b64encode(image).decode()} body = {"image": b64encode(image).decode()}
self._req_with_retries( self._req_with_retries(
"post", "post",
join(self._base_url, self._uid, "roof", "image", image_name), join(self.settings.base_url, self._uid, "roof", "image", image_name),
json=body, json=body,
) )
...@@ -122,7 +97,7 @@ class BuildingGeneric: ...@@ -122,7 +97,7 @@ class BuildingGeneric:
image = self._req_with_retries( image = self._req_with_retries(
"get", "get",
join(self._base_url, self._uid, "facade", facade_id, "image", image_name), join(self.settings.base_url, self._uid, "facade", facade_id, "image", image_name),
) )
return image["image"] return image["image"]
...@@ -130,7 +105,7 @@ class BuildingGeneric: ...@@ -130,7 +105,7 @@ class BuildingGeneric:
"""Get segmentation vectors for the specified item (eg: door) from Hbase""" """Get segmentation vectors for the specified item (eg: door) from Hbase"""
vectors = self._req_with_retries( vectors = self._req_with_retries(
"get", join(self._base_url, self._uid, "facade", facade_id, item, "vectors") "get", join(self.settings.base_url, self._uid, "facade", facade_id, item, "vectors")
) )
return vectors return vectors
...@@ -142,7 +117,7 @@ class BuildingGeneric: ...@@ -142,7 +117,7 @@ class BuildingGeneric:
body = {"image": b64encode(image).decode()} body = {"image": b64encode(image).decode()}
self._req_with_retries( self._req_with_retries(
"post", "post",
join(self._base_url, self._uid, "facade", facade_id, "image", image_name), join(self.settings.base_url, self._uid, "facade", facade_id, "image", image_name),
json=body, json=body,
) )
...@@ -151,14 +126,14 @@ class BuildingGeneric: ...@@ -151,14 +126,14 @@ class BuildingGeneric:
body = {"metadata": payload} body = {"metadata": payload}
self._req_with_retries( self._req_with_retries(
"post", "post",
join(self._base_url, self._uid, "facade", facade_id, "metadata", name), join(self.settings.base_url, self._uid, "facade", facade_id, "metadata", name),
json=body, json=body,
) )
def register_error_for_facade(self, error_code: str, facade_id: str): def register_error_for_facade(self, error_code: str, facade_id: str):
"""Add an error at facade level to ES doc""" """Add an error at facade level to ES doc"""
url = join(self._base_url, self._uid, "facade", facade_id, "errors") url = join(self.settings.base_url, self._uid, "facade", facade_id, "errors")
payload = {"error_code": error_code} payload = {"error_code": error_code}
return self._force_update_with_version(payload=payload, url=url) return self._force_update_with_version(payload=payload, url=url)
...@@ -212,25 +187,25 @@ class BuildingGeneric: ...@@ -212,25 +187,25 @@ class BuildingGeneric:
for f in self._building["facade"] for f in self._building["facade"]
] ]
url = join(self._base_url, self._uid) url = join(self.settings.base_url, self._uid)
self._update_with_version({"facade": facade}, url=url) self._update_with_version({"facade": facade}, url=url)
self.fetch() self.fetch()
# ----------------- Req methods --------------------- # ----------------- Req methods ---------------------
@staticmethod
@retry(stop_max_attempt_number=MAX_RETRIES, wait_fixed=WAIT_BETWEEN_RETRIES_IN_MS) @retry(stop_max_attempt_number=MAX_RETRIES, wait_fixed=WAIT_BETWEEN_RETRIES_IN_MS)
def _req_with_retries( def _req_with_retries(
self,
method: str, method: str,
url: str, url: str,
json: Optional[dict] = None, json: Optional[dict] = None,
headers: Optional[dict] = None, headers: Optional[dict] = None,
): ):
"""Request method. Retry if it failed""" """Request method. Retry if it failed"""
res = BuildingGeneric._req(method=method, url=url, json=json, headers=headers) res = self._req(method=method, url=url, json=json, headers=headers)
return res return res
@staticmethod
def _req( def _req(
self,
method: str, method: str,
url: str, url: str,
json: Optional[dict] = None, json: Optional[dict] = None,
...@@ -240,7 +215,7 @@ class BuildingGeneric: ...@@ -240,7 +215,7 @@ class BuildingGeneric:
if headers is None: if headers is None:
headers = {} headers = {}
headers = {**headers, "Api-Key": BuildingGeneric.api_key} headers = {**headers, "Api-Key": self.settings.api_key}
res = requests.request(method, url, json=json, headers=headers) res = requests.request(method, url, json=json, headers=headers)
res.raise_for_status() res.raise_for_status()
try: try:
......
from MaxIcsRegistry import MaxIcsRegistry
class Settings:
def __init__(self, staging):
registry = MaxIcsRegistry.from_env(staging=False, skip_delay=True)
building_center_info = registry.get_info("building-knowledge-information-center")
self.api_key = building_center_info["api_in"][registry.node_id]["key"]
self.base_url = "http://{}:{}/api/buildings/".format(
building_center_info["service_addr"], building_center_info["service_port"]
)
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment