From c1e7b3c6d6cf19e39c17bade632e23dd6565e506 Mon Sep 17 00:00:00 2001 From: Daniel Rheinbay Date: Sun, 6 Dec 2020 22:53:48 +0100 Subject: [PATCH] Use f strings, fix spelling of retrieve * Use Python 3's f strings to format strings. * Fix spelling of "retrieve" (instead of "retrive") --- config.py | 10 +++--- custom_components/mercedesmeapi/oauth.py | 20 +++++------ custom_components/mercedesmeapi/query.py | 4 +-- custom_components/mercedesmeapi/resources.py | 37 ++++++++++--------- mercedes_me_api.py | 4 +-- mercedes_me_api.sh | 12 +++---- oauth.py | 20 +++++------ query.py | 4 +-- resources.py | 38 ++++++++++---------- 9 files changed, 74 insertions(+), 75 deletions(-) diff --git a/config.py b/config.py index e20dce9..a728330 100644 --- a/config.py +++ b/config.py @@ -36,27 +36,27 @@ class MercedesMeConfig: # Read Credentials from file if not os.path.isfile(self.credentials_file): - _LOGGER.error ("Credential File " + self.credentials_file + " not found") + _LOGGER.error (f"Credential File {self.credentials_file} not found") return False try: f = ConfigObj(self.credentials_file) except Exception: - _LOGGER.error ("Wrong "+ self.credentials_file + " file found") + _LOGGER.error (f"Wrong {self.credentials_file} file found") return False # Client ID self.client_id = f.get(CONF_CLIENT_ID) if not self.client_id: - _LOGGER.error ("No "+ CONF_CLIENT_ID + " found in the configuration") + _LOGGER.error ("No {CONF_CLIENT_ID} found in the configuration") return False # Client Secret self.client_secret = f.get(CONF_CLIENT_SECRET) if not self.client_secret: - _LOGGER.error ("No "+ CONF_CLIENT_SECRET + " found in the configuration") + _LOGGER.error ("No {CONF_CLIENT_SECRET} found in the configuration") return False # Vehicle ID self.vin = f.get(CONF_VEHICLE_ID) if not self.vin: - _LOGGER.error ("No "+ CONF_VEHICLE_ID + " found in the configuration") + _LOGGER.error ("No {CONF_VEHICLE_ID} found in the configuration") return False # Read Token self.token = MercedesMeOauth(self.client_id, self.client_secret) diff --git a/custom_components/mercedesmeapi/oauth.py b/custom_components/mercedesmeapi/oauth.py index ac50638..b7fd4df 100644 --- a/custom_components/mercedesmeapi/oauth.py +++ b/custom_components/mercedesmeapi/oauth.py @@ -14,8 +14,8 @@ from .const import * from .query import * URL_OAUTH_BASE = "https://id.mercedes-benz.com/as" -URL_OAUTH_AUTH = URL_OAUTH_BASE + "/authorization.oauth2?response_type=code" -URL_OAUTH_TOKEN = URL_OAUTH_BASE + "/token.oauth2" +URL_OAUTH_AUTH = f"{URL_OAUTH_BASE}/authorization.oauth2?response_type=code" +URL_OAUTH_TOKEN = f"{URL_OAUTH_BASE}/token.oauth2" # Logger _LOGGER = logging.getLogger(__name__) @@ -39,12 +39,12 @@ class MercedesMeOauth: # Token File self.token_file = hass.config.path(TOKEN_FILE) # Base64 - b64_str = client_id + ":" + client_secret + b64_str = f"{client_id}:{client_secret}" b64_bytes = base64.b64encode( b64_str.encode('ascii') ) self.base64 = b64_bytes.decode('ascii') # Headers self.headers = { - "Authorization": "Basic " + self.base64, + "Authorization": f"Basic {self.base64}", "content-type": "application/x-www-form-urlencoded" } @@ -105,13 +105,13 @@ class MercedesMeOauth: ######################## def CheckToken(self, token): if "reason" in token: - _LOGGER.error ("Error retriving token - " + token["reason"] + " (" + str(token["code"]) + ")") + _LOGGER.error (f"Error retrieving token - {token['reason']} ({token['code']})") return False if "error" in token: if "error_description" in token: - _LOGGER.error ("Error retriving token: " + token["error_description"]) + _LOGGER.error (f"Error retrieving token: {token['error_description']}") else: - _LOGGER.error ("Error retriving token: " + token["error"]) + _LOGGER.error (f"Error retrieving token: {token['error']}") return False if len(token) == 0: _LOGGER.error ("Empty token found.") @@ -137,11 +137,11 @@ class MercedesMeOauth: ) print( "Open the browser and insert this link:\n" ) - print(auth_url + "\n") + print(f"{auth_url}\n") print( "Copy the code in the url:") auth_code = input() - data = "grant_type=authorization_code&code=" + auth_code + "&redirect_uri=" + REDIRECT_URL + data = f"grant_type=authorization_code&code={auth_code}&redirect_uri={REDIRECT_URL}" token = GetToken(URL_OAUTH_TOKEN, self.headers, data) # Check Token @@ -160,7 +160,7 @@ class MercedesMeOauth: ######################## def RefreshToken(self): - data = "grant_type=refresh_token&refresh_token=" + self.refresh_token + data = f"grant_type=refresh_token&refresh_token={self.refresh_token}" token = GetToken(URL_OAUTH_TOKEN, self.headers, data) # Check Token diff --git a/custom_components/mercedesmeapi/query.py b/custom_components/mercedesmeapi/query.py index c945be3..6a148ee 100644 --- a/custom_components/mercedesmeapi/query.py +++ b/custom_components/mercedesmeapi/query.py @@ -22,7 +22,7 @@ def GetResource(resourceURL, config): # Set Header headers = { "accept": "application/json;charset=utf-8", - "authorization": "Bearer "+ config.token.access_token + "authorization": f"Bearer {config.token.access_token}" } # Send Request @@ -69,7 +69,7 @@ def GetToken(tokenURL, headers, data): try: data = res.json() except ValueError: - _LOGGER.error ("Error retriving token " + str(res.status_code)) + _LOGGER.error (f"Error retrieving token {res.status_code}") data = { "reason": "No Data", "code" : res.status_code } diff --git a/custom_components/mercedesmeapi/resources.py b/custom_components/mercedesmeapi/resources.py index a6fbece..8a7b629 100644 --- a/custom_components/mercedesmeapi/resources.py +++ b/custom_components/mercedesmeapi/resources.py @@ -66,7 +66,7 @@ class MercedesMeResource (Entity): @property def name(self): """Return the name of the sensor.""" - return self._vin + "_" + self._name + return f"{self._vin}_{self.name}" @property def state(self): @@ -107,7 +107,7 @@ class MercedesMeResources: resources = None if not os.path.isfile(self.resources_file): - # Resources File not present - Retriving new one from server + # Resources File not present - Retrieving new one from server _LOGGER.error ("Resource File missing - Creating a new one.") found = False else: @@ -124,10 +124,10 @@ class MercedesMeResources: if ( not found ): # Not valid or file missing - resources = self.RetriveResourcesList() + resources = self.RetrieveResourcesList() if( resources == None ): # Not found or wrong - _LOGGER.error ("Error retriving resource list.") + _LOGGER.error ("Error retrieving resource list.") return False else: # import and write @@ -144,13 +144,13 @@ class MercedesMeResources: ######################## def CheckResources(self, resources): if "reason" in resources: - _LOGGER.error ("Error retriving available resources - " + resources["reason"] + " (" + str(resources["code"]) + ")") + _LOGGER.error (f"Error retrieving available resources - {resources['reason']} ({resources['code']})") return False if "error" in resources: if "error_description" in resources: - _LOGGER.error ("Error retriving resources: " + resources["error_description"]) + _LOGGER.error (f"Error retrieving resources: {resources['error_description']}") else: - _LOGGER.error ("Error retriving resources: " + resources["error"]) + _LOGGER.error (f"Error retrieving resources: {resources['error']}") return False if len(resources) == 0: _LOGGER.error ("Empty resources found.") @@ -158,13 +158,13 @@ class MercedesMeResources: return True ######################## - # Retrive Resources List + # Retrieve Resources List ######################## - def RetriveResourcesList(self): - resURL = URL_RES_PREFIX + "/vehicles/" + self.mercedesConfig.vin + "/resources" + def RetrieveResourcesList(self): + resURL = f"{URL_RES_PREFIX}/vehicles/{self.mercedesConfig.vin}/resources" resources = GetResource(resURL, self.mercedesConfig) if not self.CheckResources(resources): - _LOGGER.error ("Error retriving available resources") + _LOGGER.error ("Error retrieving available resources") return None else: return resources @@ -195,9 +195,9 @@ class MercedesMeResources: # Print Available Resources ######################## def PrintAvailableResources(self): - print ("Found %d resources" % len(self.database) + ":") + print (f"Found {len(self.database)} resources:") for res in self.database: - print (res._name + ": " + URL_RES_PREFIX + res._href) + print (f"{res._name}: {URL_RES_PREFIX}{res._href}") ######################## # Print Resources State @@ -205,18 +205,17 @@ class MercedesMeResources: def PrintResourcesState(self, valid = True): for res in self.database: if((not valid) | res._valid): - print (res._name + ":") - print ("\tvalid: " + str(res._valid)) - print ("\tstate: " + res._state) - print ("\ttimestamp: " + str(res._timestamp)) - print ("\tlast_update: " + str(res._lastupdate)) + print (f"{res._name}:") + print (f"\tvalid: {res._valid}") + print (f"\tstate: {res._state}") + print (f"\ttimestamp: {res._timestamp}") ######################## # Update Resources State ######################## def UpdateResourcesState(self): for res in self.database: - result = GetResource(URL_RES_PREFIX + res._href, self.mercedesConfig) + result = GetResource(f"{URL_RES_PREFIX}{res._href}", self.mercedesConfig) if not "reason" in result: res.UpdateState(result[res._name]["value"], result[res._name]["timestamp"]) # Write Resource File diff --git a/mercedes_me_api.py b/mercedes_me_api.py index 3a7ef69..a24f91d 100644 --- a/mercedes_me_api.py +++ b/mercedes_me_api.py @@ -31,8 +31,8 @@ def ParseInput(): parser = argparse.ArgumentParser() parser.add_argument('-t', '--token', action='store_true', help="Procedure to obtatin the Access Token") parser.add_argument('-r', '--refresh', action='store_true', help="Procedure to refresh the Access Token") - parser.add_argument('-s', '--status', action='store_true', help="Retrive the Status of your Vehicle") - parser.add_argument('-R', '--resources', action='store_true', help="Retrive the list of available resources of your Vehicle") + parser.add_argument('-s', '--status', action='store_true', help="Retrieve the Status of your Vehicle") + parser.add_argument('-R', '--resources', action='store_true', help="Retrieve the list of available resources of your Vehicle") parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + VERSION) if len(sys.argv)==1: diff --git a/mercedes_me_api.sh b/mercedes_me_api.sh index 3b64e01..f37dcb8 100755 --- a/mercedes_me_api.sh +++ b/mercedes_me_api.sh @@ -6,7 +6,7 @@ # # Change log: # 28/09/2020 - 0.1 - First Issue -# 18/10/2020 - 0.2 - Added the possibility to retrive the list of resources available +# 18/10/2020 - 0.2 - Added the possibility to retrieve the list of resources available # 03/12/2020 - 0.3 - Fix in resources list # Script Name & Version @@ -55,10 +55,10 @@ function usage () echo "Arguments:" echo " -t, --token Procedure to obtatin the Access Token (stored into $TOKEN_FILE)" echo " -r, --refresh Procedure to refresh the Access Token (stored into $TOKEN_FILE)" - echo " -f, --fuel Retrive the Fuel Status of your Vehicle" - echo " -l, --lock Retrive the Lock Status of your Vehicle" - echo " -s, --status Retrive the General Status of your Vehicle" - echo " -R, --resources Retrive the list of available resources of your Vehicle" + echo " -f, --fuel Retrieve the Fuel Status of your Vehicle" + echo " -l, --lock Retrieve the Lock Status of your Vehicle" + echo " -s, --status Retrieve the General Status of your Vehicle" + echo " -R, --resources Retrieve the list of available resources of your Vehicle" exit } @@ -162,7 +162,7 @@ function printStatus () for r in "$@" do - echo "Retriving $r:" + echo "Retrieving $r:" curl -X GET "$RES_URL/$r" -H "accept: application/json;charset=utf-8" -H "authorization: Bearer $ACCESS_TOKEN" echo done diff --git a/oauth.py b/oauth.py index 650c8de..d0f405d 100644 --- a/oauth.py +++ b/oauth.py @@ -14,8 +14,8 @@ from const import * from query import * URL_OAUTH_BASE = "https://id.mercedes-benz.com/as" -URL_OAUTH_AUTH = URL_OAUTH_BASE + "/authorization.oauth2?response_type=code" -URL_OAUTH_TOKEN = URL_OAUTH_BASE + "/token.oauth2" +URL_OAUTH_AUTH = f"{URL_OAUTH_BASE}/authorization.oauth2?response_type=code" +URL_OAUTH_TOKEN = f"{URL_OAUTH_BASE}/token.oauth2" # Logger _LOGGER = logging.getLogger(__name__) @@ -39,12 +39,12 @@ class MercedesMeOauth: # Token File self.token_file = TOKEN_FILE # Base64 - b64_str = client_id + ":" + client_secret + b64_str = f"{client_id}:{client_secret}" b64_bytes = base64.b64encode( b64_str.encode('ascii') ) self.base64 = b64_bytes.decode('ascii') # Headers self.headers = { - "Authorization": "Basic " + self.base64, + "Authorization": f"Basic {self.base64}", "content-type": "application/x-www-form-urlencoded" } @@ -104,13 +104,13 @@ class MercedesMeOauth: ######################## def CheckToken(self, token): if "reason" in token: - _LOGGER.error ("Error retriving token - " + token["reason"] + " (" + str(token["code"]) + ")") + _LOGGER.error (f"Error retrieving token - {token['reason']} ({token['code']})") return False if "error" in token: if "error_description" in token: - _LOGGER.error ("Error retriving token: " + token["error_description"]) + _LOGGER.error (f"Error retrieving token: {token['error_description']}") else: - _LOGGER.error ("Error retriving token: " + token["error"]) + _LOGGER.error (f"Error retrieving token: {token['error']}") return False if len(token) == 0: _LOGGER.error ("Empty token found.") @@ -136,11 +136,11 @@ class MercedesMeOauth: ) print( "Open the browser and insert this link:\n" ) - print(auth_url + "\n") + print(f"{auth_url}\n") print( "Copy the code in the url:") auth_code = input() - data = "grant_type=authorization_code&code=" + auth_code + "&redirect_uri=" + REDIRECT_URL + data = f"grant_type=authorization_code&code={auth_code}&redirect_uri={REDIRECT_URL}" token = GetToken(URL_OAUTH_TOKEN, self.headers, data) # Check Token @@ -159,7 +159,7 @@ class MercedesMeOauth: ######################## def RefreshToken(self): - data = "grant_type=refresh_token&refresh_token=" + self.refresh_token + data = f"grant_type=refresh_token&refresh_token={self.refresh_token}" token = GetToken(URL_OAUTH_TOKEN, self.headers, data) # Check Token diff --git a/query.py b/query.py index 733c6bd..72d0574 100644 --- a/query.py +++ b/query.py @@ -22,7 +22,7 @@ def GetResource(resourceURL, config): # Set Header headers = { "accept": "application/json;charset=utf-8", - "authorization": "Bearer "+ config.token.access_token + "authorization": f"Bearer {config.token.access_token}" } # Send Request @@ -69,7 +69,7 @@ def GetToken(tokenURL, headers, data): try: data = res.json() except ValueError: - _LOGGER.error ("Error retriving token " + str(res.status_code)) + _LOGGER.error (f"Error retrieving token {res.status_code}") data = { "reason": "No Data", "code" : res.status_code } diff --git a/resources.py b/resources.py index 3dcdd57..d56e947 100644 --- a/resources.py +++ b/resources.py @@ -63,7 +63,7 @@ class MercedesMeResource: def name(self): """Return the name of the sensor.""" - return self._vin + "_" + self._name + return f"{self._vin}_{self.name}" def state(self): """Return state for the sensor.""" @@ -106,7 +106,7 @@ class MercedesMeResources: resources = None if not os.path.isfile(self.resources_file): - # Resources File not present - Retriving new one from server + # Resources File not present - Retrieving new one from server _LOGGER.error ("Resource File missing - Creating a new one.") found = False else: @@ -123,10 +123,10 @@ class MercedesMeResources: if ( not found ): # Not valid or file missing - resources = self.RetriveResourcesList() + resources = self.RetrieveResourcesList() if( resources == None ): # Not found or wrong - _LOGGER.error ("Error retriving resource list.") + _LOGGER.error ("Error retrieving resource list.") return False else: # import and write @@ -143,13 +143,13 @@ class MercedesMeResources: ######################## def CheckResources(self, resources): if "reason" in resources: - _LOGGER.error ("Error retriving available resources - " + resources["reason"] + " (" + str(resources["code"]) + ")") + _LOGGER.error (f"Error retrieving available resources - {resources['reason']} ({resources['code']})") return False if "error" in resources: if "error_description" in resources: - _LOGGER.error ("Error retriving resources: " + resources["error_description"]) + _LOGGER.error (f"Error retrieving resources: {resources['error_description']}") else: - _LOGGER.error ("Error retriving resources: " + resources["error"]) + _LOGGER.error (f"Error retrieving resources: {resources['error']}") return False if len(resources) == 0: _LOGGER.error ("Empty resources found.") @@ -157,13 +157,13 @@ class MercedesMeResources: return True ######################## - # Retrive Resources List + # Retrieve Resources List ######################## - def RetriveResourcesList(self): - resURL = URL_RES_PREFIX + "/vehicles/" + self.mercedesConfig.vin + "/resources" + def RetrieveResourcesList(self): + resURL = f"{URL_RES_PREFIX}/vehicles/{self.mercedesConfig.vin}/resources" resources = GetResource(resURL, self.mercedesConfig) if not self.CheckResources(resources): - _LOGGER.error ("Error retriving available resources") + _LOGGER.error ("Error retrieving available resources") return None else: return resources @@ -194,9 +194,9 @@ class MercedesMeResources: # Print Available Resources ######################## def PrintAvailableResources(self): - print ("Found %d resources" % len(self.database) + ":") + print (f"Found {len(self.database)} resources:") for res in self.database: - print (res._name + ": " + URL_RES_PREFIX + res._href) + print (f"{res._name}: {URL_RES_PREFIX}{res._href}") ######################## # Print Resources State @@ -204,18 +204,18 @@ class MercedesMeResources: def PrintResourcesState(self, valid = True): for res in self.database: if((not valid) | res._valid): - print (res._name + ":") - print ("\tvalid: " + str(res._valid)) - print ("\tstate: " + res._state) - print ("\ttimestamp: " + str(res._timestamp)) - print ("\tlast_update: " + str(res._lastupdate)) + print (f"{res._name}:") + print (f"\tvalid: {res._valid}") + print (f"\tstate: {res._state}") + print (f"\ttimestamp: {res._timestamp}") + print (f"\tlast_update: {res._lastupdate}") ######################## # Update Resources State ######################## def UpdateResourcesState(self): for res in self.database: - result = GetResource(URL_RES_PREFIX + res._href, self.mercedesConfig) + result = GetResource(f"{URL_RES_PREFIX}{res._href}", self.mercedesConfig) if not "reason" in result: res.UpdateState(result[res._name]["value"], result[res._name]["timestamp"]) # Write Resource File -- 2.47.3