Skip to content

Commit

Permalink
Merge pull request #120 from mkudlej/pylint_fixes
Browse files Browse the repository at this point in the history
Pylint fixes
  • Loading branch information
Marian Ganisin authored Feb 22, 2022
2 parents 4aeed3d + b6094e1 commit 7c0e541
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 33 deletions.
6 changes: 3 additions & 3 deletions threescale_api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,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

Expand All @@ -37,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"]
}
Expand All @@ -53,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"],
Expand Down
8 changes: 4 additions & 4 deletions threescale_api/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 6 additions & 2 deletions threescale_api/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -286,6 +286,10 @@ def parent(self) -> 'DefaultResource':
def parent(self, parent):
self.client.parent = parent

@parent.setter
def parent(self, parent):
self.client.parent = parent

@property
def entity_name(self) -> Optional[str]:
return self[self._entity_name]
Expand Down
4 changes: 2 additions & 2 deletions threescale_api/errors.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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)
43 changes: 21 additions & 22 deletions threescale_api/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -252,22 +252,22 @@ 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)
instance = utils.extract_response(response=response)
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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -496,15 +497,15 @@ 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)
instance = self._create_instance(response=response)
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)
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -1270,7 +1269,7 @@ def permissions(self) -> 'UserPermissionsClient':


class AccountPlan(DefaultResource):
def __init__(self, entity_name='name', **kwargs):
def __init__(self, entity_name='system_name', **kwargs):
super().__init__(entity_name=entity_name, **kwargs)


Expand Down
3 changes: 3 additions & 0 deletions threescale_api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()])
Expand All @@ -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))

Expand Down

0 comments on commit 7c0e541

Please sign in to comment.