From 5eb566b43589fd792d642acb8f723688d3586cfb Mon Sep 17 00:00:00 2001 From: Alvaro Tinoco Date: Mon, 20 Sep 2021 13:03:00 +0000 Subject: [PATCH] refactor: remove syncrhonous code BREAKING CHANGE --- datadis/__init__.py | 182 +++++++++++++++++++++++------------------- datadis/concurrent.py | 156 ------------------------------------ 2 files changed, 101 insertions(+), 237 deletions(-) delete mode 100644 datadis/concurrent.py diff --git a/datadis/__init__.py b/datadis/__init__.py index e670ccc..7356f28 100644 --- a/datadis/__init__.py +++ b/datadis/__init__.py @@ -1,19 +1,24 @@ from typing import List, Literal from datadis.types import ( - ConsumptionData, ContractDetail, MaxPower, Supplie, dict_to_typed) + ConsumptionData, + ContractDetail, + MaxPower, + Supplie, + dict_to_typed, +) import httpx -_HOST = 'https://datadis.es' +_HOST = "https://datadis.es" _ENDPOINTS = { - 'get_token': f'{_HOST}/nikola-auth/tokens/login', - 'get_supplies': f'{_HOST}/api-private/api/get-supplies', - 'get_contract_detail': f'{_HOST}/api-private/api/get-contract-detail', - 'get_consumption_data': f'{_HOST}/api-private/api/get-consumption-data', - 'get_max_power': f'{_HOST}/api-private/api/get-max-power', + "get_token": f"{_HOST}/nikola-auth/tokens/login", + "get_supplies": f"{_HOST}/api-private/api/get-supplies", + "get_contract_detail": f"{_HOST}/api-private/api/get-contract-detail", + "get_consumption_data": f"{_HOST}/api-private/api/get-consumption-data", + "get_max_power": f"{_HOST}/api-private/api/get-max-power", } -def get_token(username: str, password: str) -> str: +async def get_token(username: str, password: str) -> str: """Get authentication token for private api Args: @@ -26,15 +31,16 @@ def get_token(username: str, password: str) -> str: Returns: str: Bearer token """ - credentials = {'username': username, 'password': password} - r = httpx.post(_ENDPOINTS['get_token'], data=credentials) - if r.status_code == 200: - return r.text - else: - raise ConnectionError(f'Error: {r.json()["message"]}') + credentials = {"username": username, "password": password} + async with httpx.AsyncClient() as client: + r = await client.post(_ENDPOINTS["get_token"], data=credentials) + if r.status_code == 200: + return r.text + else: + raise ConnectionError(f'Error: {r.json()["message"]}') -def get_supplies(token: str) -> List[Supplie]: +async def get_supplies(token: str) -> List[Supplie]: """Search all the supplies Args: @@ -46,19 +52,21 @@ def get_supplies(token: str) -> List[Supplie]: Returns: dict: A dictionary with the supplies """ - headers = {'Authorization': f'Bearer {token}'} - r = httpx.get(_ENDPOINTS['get_supplies'], headers=headers) - if r.status_code == 200: - result = [] - for supply in r.json(): - result.append(dict_to_typed(supply, Supplie)) - return result - else: - raise ConnectionError(f'Error: {r.json()["message"]}') - - -def get_contract_detail(token: str, cups: str, - distrubutor_code: int) -> List[ContractDetail]: + headers = {"Authorization": f"Bearer {token}"} + async with httpx.AsyncClient() as client: + r = await client.get(_ENDPOINTS["get_supplies"], headers=headers) + if r.status_code == 200: + result = [] + for supply in r.json(): + result.append(dict_to_typed(supply, Supplie)) + return result + else: + raise ConnectionError(f'Error: {r.json()["message"]}') + + +async def get_contract_detail( + token: str, cups: str, distrubutor_code: int +) -> List[ContractDetail]: """Search the contract detail Args: @@ -72,25 +80,32 @@ def get_contract_detail(token: str, cups: str, Returns: dict: [description] """ - headers = {'Authorization': f'Bearer {token}'} - - r = httpx.get(_ENDPOINTS['get_contract_detail'] - + f'?cups={cups}&distributorCode={distrubutor_code}', - headers=headers) - - if r.status_code == 200: - result = [] - for contract in r.json(): - result.append(dict_to_typed(contract, ContractDetail)) - return result - else: - raise ConnectionError(f'Error: {r.json()["message"]}') - - -def get_consumption_data(token: str, cups: str, - distrubutor_code: int, start_date: str, end_date: str, - measurement_type: Literal[0, 1], point_type: int - ) -> List[ConsumptionData]: + headers = {"Authorization": f"Bearer {token}"} + async with httpx.AsyncClient() as client: + r = await client.get( + _ENDPOINTS["get_contract_detail"] + + f"?cups={cups}&distributorCode={distrubutor_code}", + headers=headers, + ) + + if r.status_code == 200: + result = [] + for contract in r.json(): + result.append(dict_to_typed(contract, ContractDetail)) + return result + else: + raise ConnectionError(f'Error: {r.json()["message"]}') + + +async def get_consumption_data( + token: str, + cups: str, + distrubutor_code: int, + start_date: str, + end_date: str, + measurement_type: Literal[0, 1], + point_type: int, +) -> List[ConsumptionData]: """Search the consumption data Args: @@ -108,26 +123,29 @@ def get_consumption_data(token: str, cups: str, Returns: dict: [description] """ - headers = {'Authorization': f'Bearer {token}'} - - r = httpx.get(_ENDPOINTS['get_consumption_data'] - + f'?cups={cups}&distributorCode={distrubutor_code}' - + f'&start_date={start_date}&end_date={end_date}' - + f'&measurement_type={measurement_type}' - + f'&point_type={point_type}', - headers=headers) - - if r.status_code == 200: - result = [] - for contract in r.json(): - result.append(dict_to_typed(contract, ConsumptionData)) - return result - else: - raise ConnectionError(f'Error: {r.json()["message"]}') - - -def get_max_power(token: str, cups: str, distrubutor_code: int, - start_date: str, end_date: str) -> List[MaxPower]: + headers = {"Authorization": f"Bearer {token}"} + async with httpx.AsyncClient() as client: + r = await client.get( + _ENDPOINTS["get_consumption_data"] + + f"?cups={cups}&distributorCode={distrubutor_code}" + + f"&start_date={start_date}&end_date={end_date}" + + f"&measurement_type={measurement_type}" + + f"&point_type={point_type}", + headers=headers, + ) + + if r.status_code == 200: + result = [] + for contract in r.json(): + result.append(dict_to_typed(contract, ConsumptionData)) + return result + else: + raise ConnectionError(f'Error: {r.json()["message"]}') + + +async def get_max_power( + token: str, cups: str, distrubutor_code: int, start_date: str, end_date: str +) -> List[MaxPower]: """Search the maximum power and the result will appear in kW Args: @@ -143,17 +161,19 @@ def get_max_power(token: str, cups: str, distrubutor_code: int, Returns: dict: [description] """ - headers = {'Authorization': f'Bearer {token}'} - - r = httpx.get(_ENDPOINTS['get_max_power'] - + f'?cups={cups}&distributorCode={distrubutor_code}' - + f'&start_date={start_date}&end_date={end_date}', - headers=headers) - - if r.status_code == 200: - result = [] - for contract in r.json(): - result.append(dict_to_typed(contract, MaxPower)) - return result - else: - raise ConnectionError(f'Error: {r.json()["message"]}') + headers = {"Authorization": f"Bearer {token}"} + async with httpx.AsyncClient() as client: + r = await client.get( + _ENDPOINTS["get_max_power"] + + f"?cups={cups}&distributorCode={distrubutor_code}" + + f"&start_date={start_date}&end_date={end_date}", + headers=headers, + ) + + if r.status_code == 200: + result = [] + for contract in r.json(): + result.append(dict_to_typed(contract, MaxPower)) + return result + else: + raise ConnectionError(f'Error: {r.json()["message"]}') diff --git a/datadis/concurrent.py b/datadis/concurrent.py deleted file mode 100644 index c0d79ad..0000000 --- a/datadis/concurrent.py +++ /dev/null @@ -1,156 +0,0 @@ -from datadis.types import ( - ConsumptionData, ContractDetail, MaxPower, Supplie, dict_to_typed) -from typing import List, Literal -import httpx -from datadis import _ENDPOINTS - - -async def get_token(username: str, password: str) -> str: - """Get authentication token for private api - - Args: - username (str): NIF/NIE associated with the account - password (str): Password for the account - - Raises: - Exception: If the authentication fails - - Returns: - str: Bearer token - """ - credentials = {'username': username, 'password': password} - async with httpx.AsyncClient() as client: - r = await client.post(_ENDPOINTS['get_token'], data=credentials) - if r.status_code == 200: - return r.text - else: - raise ConnectionError(f'Error: {r.json()["message"]}') - - -async def get_supplies(token: str) -> List[Supplie]: - """Search all the supplies - - Args: - token (str): Bearer token - - Raises: - Exception: If the authentication fails - - Returns: - dict: A dictionary with the supplies - """ - headers = {'Authorization': f'Bearer {token}'} - async with httpx.AsyncClient() as client: - r = await client.get(_ENDPOINTS['get_supplies'], headers=headers) - if r.status_code == 200: - result = [] - for supply in r.json(): - result.append(dict_to_typed(supply, Supplie)) - return result - else: - raise ConnectionError(f'Error: {r.json()["message"]}') - - -async def get_contract_detail(token: str, cups: str, - distrubutor_code: int) -> List[ContractDetail]: - """Search the contract detail - - Args: - token (str): Bearer token - cups (str): Cups code. Get it from get_supplies - distrubutor_code (int): Distributor code. Get it from get_supplies - - Raises: - Exception: [description] - - Returns: - dict: [description] - """ - headers = {'Authorization': f'Bearer {token}'} - async with httpx.AsyncClient() as client: - r = await client.get( - _ENDPOINTS['get_contract_detail'] - + f'?cups={cups}&distributorCode={distrubutor_code}', - headers=headers) - - if r.status_code == 200: - result = [] - for contract in r.json(): - result.append(dict_to_typed(contract, ContractDetail)) - return result - else: - raise ConnectionError(f'Error: {r.json()["message"]}') - - -async def get_consumption_data(token: str, cups: str, distrubutor_code: int, - start_date: str, end_date: str, - measurement_type: Literal[0, 1], point_type: int - ) -> List[ConsumptionData]: - """Search the consumption data - - Args: - token (str): Bearer token - cups (str): Cups code. Get it from get_supplies - start_date (str): start date beetween search data. Format: YYYY/MM/dd - end_date (str): end date beetween search data. Format: YYYY/MM/dd - measurement_type (str): 0 -> Hourly, 1 -> quarter hourly - pointType (str): Point type code, get it from get-supplies - distrubutor_code (int): Distributor code. Get it from get_supplies - - Raises: - Exception: [description] - - Returns: - dict: [description] - """ - headers = {'Authorization': f'Bearer {token}'} - async with httpx.AsyncClient() as client: - r = await client.get( - _ENDPOINTS['get_consumption_data'] - + f'?cups={cups}&distributorCode={distrubutor_code}' - + f'&start_date={start_date}&end_date={end_date}' - + f'&measurement_type={measurement_type}' - + f'&point_type={point_type}', - headers=headers) - - if r.status_code == 200: - result = [] - for contract in r.json(): - result.append(dict_to_typed(contract, ConsumptionData)) - return result - else: - raise ConnectionError(f'Error: {r.json()["message"]}') - - -async def get_max_power(token: str, cups: str, distrubutor_code: int, - start_date: str, end_date: str) -> List[MaxPower]: - """Search the maximum power and the result will appear in kW - - Args: - token (str): Bearer token - cups (str): Cups code. Get it from get_supplies - start_date (str): start date beetween search data. Format: YYYY/MM - end_date (str): end date beetween search data. Format: YYYY/MM - distrubutor_code (int): Distributor code. Get it from get_supplies - - Raises: - Exception: [description] - - Returns: - dict: [description] - """ - headers = {'Authorization': f'Bearer {token}'} - async with httpx.AsyncClient() as client: - r = await client.get( - _ENDPOINTS['get_max_power'] - + f'?cups={cups}&distributorCode={distrubutor_code}' - + f'&start_date={start_date}&end_date={end_date}', - headers=headers) - - if r.status_code == 200: - result = [] - for contract in r.json(): - result.append(dict_to_typed(contract, MaxPower)) - return result - else: - raise ConnectionError(f'Error: {r.json()["message"]}')