[docs]@dataclassclassAPIClient:"""A wrapper around ``httpx.AsyncClient`` to yield a new client."""base_url:struser:strpassword:SecretStrtimeout:float=3auth_method:Literal["digest","basic"]="digest"def__post_init__(self):self.client:httpx.AsyncClient|None=Noneself.lock=asyncio.Lock()asyncdef__aenter__(self):"""Yields a new client."""awaitself.lock.acquire()log.debug(f"Creating async client to {self.base_url!r} with digest.")ifself.auth_method=="digest":auth=httpx.DigestAuth(self.user,self.password.get_secret_value())elifself.auth_method=="basic":auth=(self.user,self.password.get_secret_value())else:raiseValueError(f"Invalud authentication method {self.auth_method!r}.")self.client=httpx.AsyncClient(auth=auth,base_url=self.base_url,headers={},timeout=self.timeout,)returnself.clientasyncdef__aexit__(self,exc_type,exc,tb):"""Closes the client."""self.lock.release()ifself.clientandnotself.client.is_closed:log.debug("Closing async client.")awaitself.client.aclose()
[docs]defnormalise_outlet_name(name:str):"""Returns a normalised name for an outlet."""returnname.lower().replace(" ","_")
[docs]defget_outlet_by_name(outlet_data:dict[str,OutletModel],name:str):"""Gets an outlet from a list of outlets. Parameters ---------- outlet_data The mapping of outlet name to outlet model data. name The name of the outlet to retrieve. Returns ------- outlet The outlet matching the input name. Raises ------ ValueError If the outlet cannot be found. """normalised_name=normalise_outlet_name(name)ifnormalised_nameinoutlet_data:returnoutlet_data[normalised_name]raiseValueError(f"Cannot find outlet with name {name!r}.")
[docs]defget_outlet_by_id(outlet_data:dict[str,OutletModel],id:int):"""Gets an outlet by id. Parameters ---------- outlet_data The mapping of outlet name to outlet model data. id The id of the outlet to retrieve. Returns ------- outlet The outlet matching the id. Raises ------ ValueError If the outlet cannot be found. """foroutletinoutlet_data.values():ifoutlet.id==id:returnoutletraiseValueError(f"Cannot find outlet with id {id!r}.")