diff --git a/.gitignore b/.gitignore index 11fe40c..ffcda3b 100644 --- a/.gitignore +++ b/.gitignore @@ -32,7 +32,6 @@ share/python-wheels/ .installed.cfg *.egg MANIFEST -Pipfile.lock # PyInstaller # Usually these files are written by a python script from a template diff --git a/threescale_api/auth.py b/threescale_api/auth.py index 5b98cae..39d62ce 100644 --- a/threescale_api/auth.py +++ b/threescale_api/auth.py @@ -19,7 +19,8 @@ def __call__(self, request): credentials = self.credentials if self.location == "authorization": - auth = requests.auth.HTTPBasicAuth(credentials["username"], credentials["password"]) + credentials = credentials.values() + auth = requests.auth.HTTPBasicAuth(*credentials) return auth(request) if self.location == "headers": @@ -27,7 +28,7 @@ def __call__(self, request): elif self.location == "query": request.prepare_url(request.url, credentials) else: - raise ValueError("Unknown credentials location '%s'" % self.location) + raise ValueError(f"Unknown credentials location '{self.location}'") return request @@ -36,7 +37,7 @@ class UserKeyAuth(BaseClientAuth): """Provides user_key authentication for api client calls""" def __init__(self, app, location=None): - super(UserKeyAuth, self).__init__(app, location) + super().__init__(app, location) self.credentials = { self.app.service.proxy.list()["auth_user_key"]: self.app["user_key"] } @@ -52,7 +53,7 @@ class AppIdKeyAuth(BaseClientAuth): """Provides app_id/app_key pair based authentication for api client calls""" def __init__(self, app, location=None): - super(AppIdKeyAuth, self).__init__(app, location) + super().__init__(app, location) proxy = self.app.service.proxy.list() self.credentials = { proxy["auth_app_id"]: self.app["application_id"], diff --git a/threescale_api/client.py b/threescale_api/client.py index 8e5f243..c12744f 100644 --- a/threescale_api/client.py +++ b/threescale_api/client.py @@ -262,8 +262,8 @@ def __init__(self, url: str, token: str, throws: bool = True, ssl_verify: bool = self._token = token self._throws = throws self._ssl_verify = ssl_verify - log.debug(f"[REST] New instance: {url} token={token} " - f"throws={throws} ssl={ssl_verify}") + log.debug("[REST] New instance: %s token=%s throws=%s ssl=%s", url, token, throws, + ssl_verify) @property def url(self) -> str: @@ -293,8 +293,8 @@ def request(self, method='GET', url=None, path='', params: dict = None, if throws is None: throws = self._throws params.update(access_token=self._token) - log.debug(f"[{method}] ({full_url}) params={params} headers={headers} " - f"{kwargs if kwargs else ''}") + log.debug("[%s] (%s) params={%s} headers={%s} %s", method, full_url, params, headers, + kwargs if kwargs else '') response = requests.request(method=method, url=full_url, headers=headers, params=params, verify=self._ssl_verify, **kwargs) process_response = self._process_response(response, throws=throws) diff --git a/threescale_api/defaults.py b/threescale_api/defaults.py index 55ec01b..00dab29 100644 --- a/threescale_api/defaults.py +++ b/threescale_api/defaults.py @@ -187,7 +187,7 @@ def select_by(self, **params) -> List['DefaultResource']: **params: params used for selection Returns: List of resources """ - log.debug(f"[SELECT] By params: {params}") + log.debug("[SELECT] By params: %s", params) def predicate(item): for (key, val) in params.items(): @@ -238,7 +238,7 @@ def _create_instance(self, response: requests.Response, klass=None, collection: klass = klass or self._instance_klass extracted = self._extract_resource(response, collection) instance = self._instantiate(extracted=extracted, klass=klass) - log.debug(f"[INSTANCE] Created instance: {instance}") + log.debug("[INSTANCE] Created instance: %s", instance) return instance def _extract_resource(self, response, collection) -> Union[List, Dict]: diff --git a/threescale_api/errors.py b/threescale_api/errors.py index ccde43d..492e849 100644 --- a/threescale_api/errors.py +++ b/threescale_api/errors.py @@ -1,7 +1,7 @@ class ThreeScaleApiError(Exception): def __init__(self, message, *args): self.message = message - super(ThreeScaleApiError, self).__init__(message, *args) + super().__init__(message, *args) class ApiClientError(ThreeScaleApiError): @@ -13,4 +13,4 @@ def __init__(self, code, reason, body, message: str = None): msg = f"Response({self.code} {reason}): {body}" if message: msg += f"; {message}" - super(ApiClientError, self).__init__(msg) + super().__init__(msg) diff --git a/threescale_api/resources.py b/threescale_api/resources.py index 4408968..244c4e0 100644 --- a/threescale_api/resources.py +++ b/threescale_api/resources.py @@ -67,7 +67,7 @@ def url(self) -> str: return self.application_plan.plans_url + f'/metrics/{self.metric.entity_id}/limits' def list_per_app_plan(self, **kwargs): - log.info(f"[LIST] List limits per app plan: {kwargs}") + log.info("[LIST] List limits per app plan: %s", kwargs) url = self.parent.url + '/limits' response = self.rest.get(url=url, **kwargs) instance = self._create_instance(response=response) @@ -177,7 +177,7 @@ def signup(self, params: dict, **kwargs) -> 'Account': **kwargs: Optional args Returns(Account): Account instance """ - log.info(f"[SIGNUP] Create new Signup: {kwargs}") + log.info("[SIGNUP] Create new Signup: %s", kwargs) url = self.threescale_client.admin_api_url + '/signup' response = self.rest.post(url=url, json=params, **kwargs) instance = self._create_instance(response=response) @@ -191,7 +191,7 @@ def set_plan(self, entity_id: int, plan_id: int, **kwargs): **kwargs: Optional args Returns: """ - log.info(f"[PLAN] Set plan for an account({entity_id}): {plan_id}") + log.info("[PLAN] Set plan for an account(%s): %s", entity_id, plan_id) params = dict(plan_id=plan_id) url = self._entity_url(entity_id=entity_id) + '/change_plan' response = self.rest.put(url=url, json=params, **kwargs) @@ -206,7 +206,7 @@ def send_message(self, entity_id: int, body: str, **kwargs) -> Dict: **kwargs: Optional args Returns(Dict): Response """ - log.info(f"[MSG] Send message to account ({entity_id}): {body} {kwargs}") + log.info("[MSG] Send message to account (%s): %s %s", entity_id, body, kwargs) params = dict(body=body) url = self._entity_url(entity_id=entity_id) + '/messages' response = self.rest.post(url=url, json=params, **kwargs) @@ -252,7 +252,7 @@ def url(self) -> str: return self.parent.url + '/applications' def change_plan(self, entity_id: int, plan_id: int, **kwargs): - log.info(f"[PLAN] Change plan for application ({entity_id}) to {plan_id} {kwargs}") + log.info("[PLAN] Change plan for application (%s) to %s %s", entity_id, plan_id, kwargs) params = dict(plan_id=plan_id) url = self._entity_url(entity_id=entity_id) + '/change_plan' response = self.rest.put(url=url, json=params, **kwargs) @@ -260,14 +260,14 @@ def change_plan(self, entity_id: int, plan_id: int, **kwargs): return instance def customize_plan(self, entity_id: int, **kwargs): - log.info(f"[PLAN] Customize plan for application ({entity_id}) {kwargs}") + log.info("[PLAN] Customize plan for application (%s) %s", entity_id, kwargs) url = self._entity_url(entity_id=entity_id) + '/customize_plan' response = self.rest.put(url=url, **kwargs) instance = utils.extract_response(response=response) return instance def decustomize_plan(self, entity_id: int, **kwargs): - log.info(f"[PLAN] Decustomize plan for application ({entity_id}) {kwargs}") + log.info("[PLAN] Decustomize plan for application (%s) %s", entity_id, kwargs) url = self._entity_url(entity_id=entity_id) + '/decustomize_plan' response = self.rest.put(url=url, **kwargs) instance = utils.extract_response(response=response) @@ -357,8 +357,8 @@ def url(self) -> str: class Analytics(DefaultClient): def _list_by_resource(self, resource_id: int, resource_type, metric_name: str = 'hits', since=None, period: str = 'year', **kwargs): - log.info(f"List analytics by {resource_type} ({resource_id}) f" - f"or metric (#{metric_name})") + log.info("List analytics by %s (%s) for metric (#%s)", resource_type, resource_id, + metric_name) params = dict( metric_name=metric_name, since=since, @@ -388,9 +388,9 @@ def __init__(self, *args, entity_name='tenant', entity_collection='tenants', **k super().__init__(*args, entity_name=entity_name, entity_collection=entity_collection, **kwargs) - def read(self, id, **kwargs): + def read(self, entity_id, **kwargs): log.debug(self._log_message("[GET] Read Tenant", args=kwargs)) - url = self._entity_url(entity_id=id) + url = self._entity_url(entity_id=entity_id) response = self.rest.get(url=url, **kwargs) instance = self._create_instance(response=response) return instance @@ -440,7 +440,7 @@ def url(self) -> str: return self.parent.url + '/proxy' def deploy(self) -> 'Proxy': - log.info(f"[DEPLOY] {self._entity_name} to Staging") + log.info("[DEPLOY] %s to Staging", self._entity_name) url = f'{self.url}/deploy' response = self.rest.post(url) instance = self._create_instance(response=response) @@ -487,7 +487,8 @@ def list(self, **kwargs): def promote(self, version: int = 1, from_env: str = 'sandbox', to_env: str = 'production', **kwargs) -> 'Proxy': - log.info(f"[PROMOTE] {self.service} version {version} from {from_env} to {to_env}") + log.info("[PROMOTE] %s version %s from %s to %s", self.service, version, from_env, + to_env) url = f'{self.url}/{from_env}/{version}/promote' params = dict(to=to_env) kwargs.update() @@ -496,7 +497,7 @@ def promote(self, version: int = 1, from_env: str = 'sandbox', to_env: str = 'pr return instance def latest(self, env: str = "sandbox") -> 'ProxyConfig': - log.info(f"[LATEST] Get latest proxy configuration of {env}") + log.info("[LATEST] Get latest proxy configuration of %s", env) self._env = env url = self.url + '/latest' response = self.rest.get(url=url) @@ -504,7 +505,7 @@ def latest(self, env: str = "sandbox") -> 'ProxyConfig': return instance def version(self, version: int = 1, env: str = "sandbox") -> 'ProxyConfig': - log.info(f"[VERSION] Get proxy configuration of {env} of version {version}") + log.info("[VERSION] Get proxy configuration of %s of version %s", env, version) self._env = env url = f'{self.url}/{version}' response = self.rest.get(url=url) @@ -873,7 +874,7 @@ def state_update(self, entity_id: int, state: InvoiceState, **kwargs): Values allowed (depend on the previous state): cancelled, failed, paid, unpaid, pending, finalized """ - log.info(f"[Invoice] state changed for invoice ({entity_id}): {state}") + log.info("[Invoice] state changed for invoice (%s): %s", entity_id, state) params = dict(state=state.value) url = self._entity_url(entity_id) + '/state' response = self.rest.put(url=url, json=params, **kwargs) @@ -882,7 +883,7 @@ def state_update(self, entity_id: int, state: InvoiceState, **kwargs): def charge(self, entity_id: int): """Charge an Invoice.""" - log.info(f"[Invoice] charge invoice ({entity_id})") + log.info("[Invoice] charge invoice (%s)", entity_id) url = self._entity_url(entity_id) + '/charge' response = self.rest.post(url) instance = self._create_instance(response=response) @@ -974,15 +975,13 @@ def service(self) -> 'Service': def __getitem__(self, key): if "proxy_configs" in self.entity: return self.entity["proxy_configs"][key] - else: - return super().__getitem__(key) + return super().__getitem__(key) # Same problem as in __getitem__. def __len__(self): if "proxy_configs" in self.entity: return len(self.entity["proxy_configs"]) - else: - return super().__len__() + return super().__len__() class Policy(DefaultResource): diff --git a/threescale_api/utils.py b/threescale_api/utils.py index 0213fa9..dba6648 100644 --- a/threescale_api/utils.py +++ b/threescale_api/utils.py @@ -157,8 +157,10 @@ def delete(self, *args, **kwargs) -> requests.Response: def request2curl(request: requests.PreparedRequest) -> str: """Create curl command corresponding to given request""" + # pylint: disable=consider-using-f-string cmd = ["curl", "-X %s" % shlex.quote(request.method)] if request.headers: + # pylint: disable=consider-using-f-string cmd.extend([ "-H %s" % shlex.quote(f"{key}: {value}") for key, value in request.headers.items()]) @@ -168,6 +170,7 @@ def request2curl(request: requests.PreparedRequest) -> str: body = body.decode("utf-8") if len(body) > 160: body = body[:160] + "..." + # pylint: disable=consider-using-f-string cmd.append("-d %s" % shlex.quote(body)) cmd.append(shlex.quote(request.url))