exception handling

This commit is contained in:
Tyrel Souza 2021-11-04 21:48:38 -04:00
parent 291a41c9b0
commit 85b7b1fcb1
3 changed files with 19 additions and 30 deletions

34
api.py
View File

@ -4,37 +4,21 @@ import httpx
class API:
headers = {"Accept": "application/vnd.github.v3+json"}
def __init__(self, user_name: str) -> None:
self.user = self.load_user(user_name)
self.user_name = self.user["login"]
self.repos = self.load_repos() # TODO: Check if pagination
def raise_on_4xx_5xx(self, response):
response.raise_for_status()
def _get(self, url: str) -> dict:
"""Uses httpx.Client().get to send the appropriate github headers, and return the url"""
with httpx.Client(headers=self.headers) as client:
return client.get(url).json()
def _get_paged(self, url: str) -> list:
def get(self, url: str) -> list:
"""Uses httpx.Client().get to send the appropriate github headers, and return the url"""
content = []
with httpx.Client(headers=self.headers) as client:
with httpx.Client(headers=self.headers, event_hooks={'response': [self.raise_on_4xx_5xx]}) as client:
while True:
resp = client.get(url)
content.extend(resp.json())
body = resp.json()
if isinstance(body, dict):
# short circuit if not list
return body
content.extend(body)
if not resp.links.get('next'):
break
url = resp.links['next']['url']
return content
def load_user(self, user_name: str) -> dict:
"""Sets the user object"""
return self._get(f"https://api.github.com/users/{user_name}")
def load_repo(self, repo_name: str) -> dict:
"""Set the repo object"""
return self._get(f"https://api.github.com/repos/{self.user_name}/{repo_name}")
def load_repos(self) -> dict:
"""Set the users repos"""
return self._get_paged(f"https://api.github.com/users/{self.user_name}/repos")

3
cli.py
View File

@ -7,7 +7,8 @@ import httpx
def main():
user_name = Prompt.ask("Username?")
gh = GHub()
gh.load_user(user_name=user_name)
success = gh.load_user(user_name=user_name)
if success:
print(gh.repos_table())

10
ghub.py
View File

@ -2,6 +2,7 @@ from rich.table import Table
from rich.prompt import Prompt
from rich import print
from api import API
import httpx
class GHub:
@ -10,9 +11,12 @@ class GHub:
def load_user(self, user_name: str) -> None:
self.user_name = user_name
self.api = API(self.user_name)
self.user = self.api.user
self.repos = self.api.repos
self.api = API()
try:
self.user = self.api.get(f"https://api.github.com/users/{user_name}")
self.repos = self.api.get(f"https://api.github.com/users/{user_name}/repos")
except httpx.HTTPStatusError as e:
print(e)
def repos_trimmed(self) -> list:
for repo in self.repos: