Skip to content
This repository has been archived by the owner on Jul 15, 2022. It is now read-only.

Commit

Permalink
Feature/removing raise for status and use request hooks (#36)
Browse files Browse the repository at this point in the history
* removed all raise_for_status and added a common hook on request

* error handling

* improved overriding custom hooks

* added hooks to the request

* typo

* correct way to concat two lists

* avoid errors on 401

* removed default hook
  • Loading branch information
sandromodarelli authored Dec 2, 2019
1 parent d21a83c commit 3aec8db
Show file tree
Hide file tree
Showing 13 changed files with 20 additions and 54 deletions.
26 changes: 20 additions & 6 deletions pystackpath/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from requests import Session
from requests import Session, HTTPError

from .stacks import Stacks
from .config import BASE_URL


class OAuth2Session(Session):
def __init__(self, clientid, apisecret):
def __init__(self, clientid, apisecret, custom_hooks: list = []):
self._clientid = clientid
self._apisecret = apisecret
self._custom_hooks = custom_hooks
self._token = ""

super(OAuth2Session, self).__init__()
Expand All @@ -30,12 +31,25 @@ def _add_auth(self, kwargs):
kwargs["headers"]["Authorization"] = "Bearer %s" % self._token
return kwargs

def _add_hooks(self, kwargs):
if self._custom_hooks:
if not "hooks" in kwargs:
kwargs["hooks"] = dict()
if not "response" in kwargs["hooks"]:
kwargs["hooks"]["response"] = list()

kwargs["hooks"]["response"] = kwargs["hooks"]["response"] + self._custom_hooks

return kwargs

def request(self, method, url, **kwargs):
kwargs = self._add_auth(kwargs)
kwargs = self._add_hooks(kwargs)
response = super(OAuth2Session, self).request(method, BASE_URL + url, **kwargs)
if response.status_code == 401:
self._refresh_token()
kwargs = self._add_auth(kwargs)
kwargs = self._add_hooks(kwargs)
response = super(OAuth2Session, self).request(method, BASE_URL + url, **kwargs)
return response

Expand All @@ -46,13 +60,13 @@ class Stackpath(object):

client = None

def __init__(self, clientid, apisecret):
def __init__(self, clientid, apisecret, custom_hooks: list = []):
self._clientid = clientid
self._apisecret = apisecret
self._init_client()
self._init_client(custom_hooks)

def _init_client(self):
self.client = OAuth2Session(self._clientid, self._apisecret)
def _init_client(self, custom_hooks):
self.client = OAuth2Session(self._clientid, self._apisecret, custom_hooks=custom_hooks)

def stacks(self):
return Stacks(self.client)
7 changes: 0 additions & 7 deletions pystackpath/stacks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ class Stacks(BaseObject):
def index(self, first="", after="", filter="", sort_by=""):
pagination = pagination_query(first=first, after=after, filter=filter, sort_by=sort_by)
response = self._client.get("/stack/v1/stacks", params=pagination)
response.raise_for_status()
items = []
for item in response.json()["results"]:
items.append(self.loaddict(item))
Expand All @@ -20,13 +19,11 @@ def index(self, first="", after="", filter="", sort_by=""):

def get(self, stack_id):
response = self._client.get(f"/stack/v1/stacks/{stack_id}")
response.raise_for_status()
return self.loaddict(response.json())

def create(self, accountid, name):
response = self._client.post("/stack/v1/stacks",
json={"accountId": accountid, "name": str(name)})
response.raise_for_status()
return self.loaddict(response.json()["stack"])

def add_subscriptions(self, subscriptions: list):
Expand All @@ -36,7 +33,6 @@ def add_subscriptions(self, subscriptions: list):
"productIds": subscriptions
}
)
response.raise_for_status()
return self

def cancel(self, reason_slug, reason_text=""):
Expand All @@ -59,7 +55,6 @@ def cancel(self, reason_slug, reason_text=""):
"reasonText": reason_text
}
)
response.raise_for_status()
return self

def purge(self, items: list) -> str:
Expand All @@ -73,7 +68,6 @@ def purge(self, items: list) -> str:
}

response = self._client.post(f"/cdn/v1/stacks/{self.id}/purge", json=data)
response.raise_for_status()

return response.json()["id"]

Expand All @@ -84,7 +78,6 @@ def purge_status(self, purge_id) -> float:
:return: The purge request's progress, ranging from 0.0 to 1.0.
"""
response = self._client.get(f"/cdn/v1/stacks/{self.id}/purge/{purge_id}")
response.raise_for_status()

return response.json()["progress"]

Expand Down
3 changes: 0 additions & 3 deletions pystackpath/stacks/cdnsites/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ def disable(self):
:return: a stackpath site object with the disabled cdn site
"""
response = self._client.post(f"{self._base_api}/sites/{self.id}/disable")
response.raise_for_status()
return self

def enable(self):
Expand All @@ -57,7 +56,6 @@ def enable(self):
:return: a stackpath site object with the enabled cdn site
"""
response = self._client.post(f"{self._base_api}/sites/{self.id}/enable")
response.raise_for_status()
return self

def assign_certificate(self, certificate: Certificates):
Expand All @@ -67,7 +65,6 @@ def assign_certificate(self, certificate: Certificates):
:return:
"""
response = self._client.put(f"{self._base_api}/sites/{self.id}/certificates/{certificate.id}")
response.raise_for_status()

certificate = Certificates(self._client, f"{self._base_api}/certificates")
return certificate.loaddict(response.json()["siteCertificate"]["certificate"])
Expand Down
3 changes: 0 additions & 3 deletions pystackpath/stacks/cdnsites/scopes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ def index(self, first="", after="", filter="", sort_by="", disable_transparent_m
}
response = self._client.get(f"{self._base_api}/scopes",
params={**pagination, **params})
response.raise_for_status()
items = [self.loaddict(item) for item in response.json()["results"]]
pageinfo = PageInfo(**response.json()["pageInfo"])

Expand All @@ -33,7 +32,6 @@ def create(self, **payload):
String path The HTTP request path that is handled by a scope.
"""
response = self._client.post(f"{self._base_api}/scopes", json=payload)
response.raise_for_status()
return self.loaddict(response.json()["scope"])

def delete(self):
Expand All @@ -42,7 +40,6 @@ def delete(self):
:return: delivery domains configured on a site
"""
response = self._client.delete(f"{self._base_api}/scopes/{self.id}")
response.raise_for_status()
return self

def configuration(self):
Expand Down
2 changes: 0 additions & 2 deletions pystackpath/stacks/cdnsites/scopes/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ def get(self):
:return: site's scope configuration
"""
response = self._client.get(f"{self._base_api}/configuration")
response.raise_for_status()
return self.loaddict(response.json()["configuration"])

def update(self, **payload):
Expand All @@ -19,5 +18,4 @@ def update(self, **payload):
:return: dict with new configuration
"""
response = self._client.patch(f"{self._base_api}/configuration", data=json.dumps(payload))
response.raise_for_status()
return self.loaddict(response.json()["configuration"])
3 changes: 0 additions & 3 deletions pystackpath/stacks/cdnsites/scopes/origins.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
class Origins(BaseObject):
def index(self):
response = self._client.get(f"{self._base_api}")
response.raise_for_status()

items = list(map(lambda x: self.loaddict(x), response.json()["results"]))
pageinfo = PageInfo(**response.json()["pageInfo"])
Expand All @@ -24,7 +23,6 @@ def create(self, **payload):
Boolean dedicated Whether or not an origin is dedicated to a CDN site.
"""
response = self._client.post(f"{self._base_api}", json=payload)
response.raise_for_status()
return self.loaddict(response.json()["scopeOrigin"])

def delete(self):
Expand All @@ -34,5 +32,4 @@ def delete(self):
:return:
"""
response = self._client.delete(f"{self._base_api}")
response.raise_for_status()
return self
6 changes: 0 additions & 6 deletions pystackpath/stacks/certificates.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ class Certificates(BaseObject):
def index(self, first="", after="", filter="", sort_by=""):
pagination = pagination_query(first=first, after=after, filter=filter, sort_by=sort_by)
response = self._client.get(f"{self._base_api}/certificates", params=pagination)
response.raise_for_status()

items = list(map(lambda x: self.loaddict(x), response.json()["results"]))
pageinfo = PageInfo(**response.json()["pageInfo"])
Expand All @@ -14,7 +13,6 @@ def index(self, first="", after="", filter="", sort_by=""):

def get(self, certificate_id: str):
response = self._client.get(f"{self._base_api}/certificates/{certificate_id}")
response.raise_for_status()

return self.loaddict(response.json()["certificate"])

Expand All @@ -26,13 +24,11 @@ def add(self, certificate_string: str, key_string: str, ca_bundle_string: str =
}

response = self._client.post(f"{self._base_api}/certificates", json=data)
response.raise_for_status()

return self.loaddict(response.json()["certificate"])

def delete(self):
response = self._client.delete(f"{self._base_api}/certificates/{self.id}")
response.raise_for_status()

return self

Expand All @@ -44,12 +40,10 @@ def update(self, certificate_string = None, key_string = None, ca_bundle_string:
}

response = self._client.put(f"{self._base_api}/certificates/{self.id}", json=data)
response.raise_for_status()

return self.loaddict(response.json()["certificate"])

def renew(self):
response = self._client.post(f"{self._base_api}/certificates/{self.id}/renew")
response.raise_for_status()

return self
6 changes: 0 additions & 6 deletions pystackpath/stacks/deliverysites/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ def disable_cdn(self):
:return: a stackpath site object with the disabled cdn site
"""
response = self._client.delete(f"{self._base_api}/sites/{self.id}/cdn")
response.raise_for_status()
return self

def enable_cdn(self):
Expand All @@ -48,7 +47,6 @@ def enable_cdn(self):
:return: a stackpath site object with the enabled cdn site
"""
response = self._client.post(f"{self._base_api}/sites/{self.id}/cdn")
response.raise_for_status()
return self

def disable_waf(self):
Expand All @@ -57,7 +55,6 @@ def disable_waf(self):
:return: a stackpath site object with the disabled waf site
"""
response = self._client.delete(f"{self._base_api}/sites/{self.id}/waf")
response.raise_for_status()
return self

def enable_waf(self):
Expand All @@ -66,7 +63,6 @@ def enable_waf(self):
:return: a stackpath site object with the enabled waf site
"""
response = self._client.post(f"{self._base_api}/sites/{self.id}/waf")
response.raise_for_status()
return self

def disable_scripting(self):
Expand All @@ -75,7 +71,6 @@ def disable_scripting(self):
:return: a stackpath site object with the disabled scripting site
"""
response = self._client.delete(f"{self._base_api}/sites/{self.id}/scripting")
response.raise_for_status()
return self

def enable_scripting(self):
Expand All @@ -84,7 +79,6 @@ def enable_scripting(self):
:return: a stackpath site object with the enabled scripting site
"""
response = self._client.post(f"{self._base_api}/sites/{self.id}/scripting")
response.raise_for_status()
return self

def delivery_domains(self):
Expand Down
3 changes: 0 additions & 3 deletions pystackpath/stacks/deliverysites/delivery_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ def index(self, first="", after="", filter="", sort_by=""):
pagination = pagination_query(first=first, after=after, filter=filter, sort_by=sort_by)
response = self._client.get(f"{self._base_api}/delivery_domains",
params=pagination)
response.raise_for_status()
items = [self.loaddict(item) for item in response.json()["results"]]
pageinfo = PageInfo(**response.json()["pageInfo"])

Expand All @@ -24,7 +23,6 @@ def create(self, **payload):
String domain An individual delivery domain.
"""
response = self._client.post(f"{self._base_api}/delivery_domains", json=payload)
response.raise_for_status()
return self.loaddict(response.json()["domain"])

def delete(self):
Expand All @@ -33,5 +31,4 @@ def delete(self):
:return: delivery domains configured on a site
"""
response = self._client.delete(f"{self._base_api}/delivery_domains/{self.domain}")
response.raise_for_status()
return self
1 change: 0 additions & 1 deletion pystackpath/stacks/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,5 @@ def get(self, start_date: dt = None, end_date: dt = None, granularity="AUTO",
"site_type_filter": site_type_filter
}
)
response.raise_for_status()

return self.loaddict(response.json())
2 changes: 0 additions & 2 deletions pystackpath/stacks/wafsites/ddos.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
class Ddos(BaseObject):
def get(self):
response = self._client.get(f"{self._base_api}/ddos")
response.raise_for_status()
return self.loaddict(response.json()["ddosSettings"])

def update(self, **payload):
Expand All @@ -15,5 +14,4 @@ def update(self, **payload):
:return: dict with new rule
"""
response = self._client.patch(f"{self._base_api}/ddos", data=json.dumps(payload))
response.raise_for_status()
return self.loaddict(response.json()["ddosSettings"])
8 changes: 0 additions & 8 deletions pystackpath/stacks/wafsites/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ def index(self, first="", after="", filter="", sort_by=""):
pagination = pagination_query(first=first, after=after, filter=filter, sort_by=sort_by)
response = self._client.get(f"{self._base_api}/rules",
params=pagination)
response.raise_for_status()
items = [self.loaddict(item) for item in response.json()["rules"]]
pageinfo = PageInfo(**response.json()["pageInfo"])

return {"results": items, "pageinfo": pageinfo}

def get(self, rule_id):
response = self._client.get(f"{self._base_api}/rules/{rule_id}")
response.raise_for_status()
return self.loaddict(response.json()["rule"])

def create(self, **payload):
Expand All @@ -29,7 +27,6 @@ def create(self, **payload):
:return: dict with created rule
"""
response = self._client.post(f"{self._base_api}/rules", json=payload)
response.raise_for_status()
return self.loaddict(response.json()["rule"])

def update(self, **payload):
Expand All @@ -39,7 +36,6 @@ def update(self, **payload):
:return: dict with new rule
"""
response = self._client.patch(f"{self._base_api}/rules/{self.id}", data=json.dumps(payload))
response.raise_for_status()
return self.loaddict(response.json()["rule"])

def delete(self):
Expand All @@ -48,7 +44,6 @@ def delete(self):
:return: waf rule configured on a site
"""
response = self._client.delete(f"{self._base_api}/rules/{self.id}")
response.raise_for_status()
return self

def bulk_delete(self, ruleIds: list):
Expand All @@ -57,20 +52,17 @@ def bulk_delete(self, ruleIds: list):
:param ruleIds: The IDs of the rules to delete.
"""
response = self._client.post(f"{self._base_api}/rules/bulk_delete", data=json.dumps(dict(ruleIds=ruleIds)))
response.raise_for_status()

def enable(self):
"""
Enable a WAF rule
:param rule_id: The ID of the rule to enable
"""
response = self._client.post(f"{self._base_api}/rules/{self.id}/enable")
response.raise_for_status()

def disable(self):
"""
Disable a WAF rule
:param rule_id: The ID of the rule to disable
"""
response = self._client.post(f"{self._base_api}/rules/{self.id}/disable")
response.raise_for_status()
Loading

0 comments on commit 3aec8db

Please sign in to comment.