From 4703154b174595d3def62d9c7b3f1237f913c066 Mon Sep 17 00:00:00 2001 From: agatha Date: Tue, 12 Sep 2023 14:51:34 -0400 Subject: [PATCH] Implement PastebinClient class with self-contained paste list --- src/main.py | 24 ++++++++++++++---------- src/pastebin/client.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/src/main.py b/src/main.py index f5231d4..7980862 100644 --- a/src/main.py +++ b/src/main.py @@ -1,21 +1,25 @@ -from pastebin.client import PastebinAPI +from pastebin.client import PastebinClient def main(): - pastebin = PastebinAPI() + pastebin = PastebinClient() # Fetch public paste list - pastes = pastebin.get_public_paste_list() - for paste in pastes: - print(paste) + pastebin.populate_pastes() # Fetch full data from a few pastes to test methods - pastes[0] = pastebin.get_paste(pastes[0]) - pastes[1] = pastebin.get_paste(pastes[1]) + pastebin.fetch_paste(0) + pastebin.fetch_paste(1) - # Test filtering - fetched = list(filter(lambda x: x.fetched is True, pastes)) - print(fetched) + # Test get_pastes_by_language + py_pastes = pastebin.get_pastes_by_language("Python") + for i in py_pastes: + print(pastebin.pastes[i]) + + # Test if duplication is prevented by Paste.__hash__ + print(len(pastebin.pastes)) + pastebin.populate_pastes() + print(len(pastebin.pastes)) if __name__ == '__main__': diff --git a/src/pastebin/client.py b/src/pastebin/client.py index fcd00eb..6ab8021 100644 --- a/src/pastebin/client.py +++ b/src/pastebin/client.py @@ -39,6 +39,14 @@ class Paste: f"fetched={self.fetched})" ) + def __hash__(self): + return hash((self.title, self.href, self.lang)) + + def __eq__(self, other): + if isinstance(other, Paste): + return self.title == other.title and self.href == other.href and self.lang == other.lang + return False + class PastebinAPI: """ @@ -142,3 +150,27 @@ class PastebinAPI: paste.fetched = True return paste + + +class PastebinClient(PastebinAPI): + def __init__(self, headers=None, proxies=None, debug=False): + super().__init__(headers, proxies, debug) + self.pastes = [] + + def populate_pastes(self): + pastes_catalog = set(self.get_public_paste_list()) + self.pastes = list(set(self.pastes).union(pastes_catalog)) + + def fetch_paste(self, paste_index): + if paste_index >= len(self.pastes): + return None + return self.get_paste(self.pastes[paste_index]) + + def get_paste_list(self): + return self.pastes + + def total_pastes(self): + return len(self.pastes) + + def get_pastes_by_language(self, lang): + return [i for i, paste in enumerate(self.pastes) if paste.lang.lower() == lang.lower()] \ No newline at end of file