Skip to content
This repository was archived by the owner on Nov 20, 2022. It is now read-only.

Commit bc0c250

Browse files
committed
added __enter__ to work with __exit__, simplified exception handling
1 parent fea97d9 commit bc0c250

1 file changed

Lines changed: 12 additions & 23 deletions

File tree

src/pythonpancakes/api.py

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ def __init__(self, base_url=__BASE_URL):
2121
retries = Retry(total=3, backoff_factor=0.5, status_forcelist=[502, 503, 504])
2222
self.session.mount('https://', HTTPAdapter(max_retries=retries))
2323

24+
def __enter__(self):
25+
return self
26+
2427
def __exit__(self):
2528
self.session.close()
2629

@@ -29,21 +32,9 @@ def __get(self, request_url: str):
2932
GET request wrapper
3033
:param request_url: str
3134
"""
32-
try:
33-
response = self.session.get(request_url, timeout=self.request_timeout)
34-
except requests.exceptions.RequestException:
35-
raise
36-
37-
try:
38-
response.raise_for_status()
39-
return json.loads(response.content.decode('utf-8'))
40-
except Exception as err:
41-
try:
42-
content = json.loads(response.content.decode('utf-8'))
43-
raise ValueError(content)
44-
except json.decoder.JSONDecodeError:
45-
pass
46-
raise
35+
response = self.session.get(request_url, timeout=self.request_timeout)
36+
response.raise_for_status()
37+
return json.loads(response.content.decode('utf-8'))
4738

4839
def summary(self):
4940
"""
@@ -61,14 +52,11 @@ def tokens(self, address: str = None):
6152
:return: Dict
6253
"""
6354
if address:
64-
try:
65-
# Trim any whitespace from address
66-
address = address.replace(' ', '')
67-
# Validate provided address matches ERC20 format - does not check if the address is valid on chain!
68-
if not re.match("^0x([A-Fa-f0-9]{40})$", address):
69-
raise ValueError(address)
70-
except ValueError:
71-
return "Provided address hash is not in a valid format"
55+
# Trim any whitespace from address
56+
address = address.replace(' ', '')
57+
# Validate provided address matches ERC20 format - does not check if the address is valid on chain!
58+
if not re.match("^0x([A-Fa-f0-9]{40})$", address):
59+
raise ValueError(f"Provided address hash ({address}) is not in a valid format.")
7260

7361
url = f"{self.base_url}tokens{'/' + address if address is not None else ''}"
7462
return self.__get(url)
@@ -80,3 +68,4 @@ def pairs(self):
8068
"""
8169
url = f"{self.base_url}pairs"
8270
return self.__get(url)
71+

0 commit comments

Comments
 (0)