Implement PastebinClient class with self-contained paste list

This commit is contained in:
agatha 2023-09-12 14:51:34 -04:00
parent 9ec62c5d9b
commit 4703154b17
2 changed files with 46 additions and 10 deletions

View File

@ -1,21 +1,25 @@
from pastebin.client import PastebinAPI from pastebin.client import PastebinClient
def main(): def main():
pastebin = PastebinAPI() pastebin = PastebinClient()
# Fetch public paste list # Fetch public paste list
pastes = pastebin.get_public_paste_list() pastebin.populate_pastes()
for paste in pastes:
print(paste)
# Fetch full data from a few pastes to test methods # Fetch full data from a few pastes to test methods
pastes[0] = pastebin.get_paste(pastes[0]) pastebin.fetch_paste(0)
pastes[1] = pastebin.get_paste(pastes[1]) pastebin.fetch_paste(1)
# Test filtering # Test get_pastes_by_language
fetched = list(filter(lambda x: x.fetched is True, pastes)) py_pastes = pastebin.get_pastes_by_language("Python")
print(fetched) 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__': if __name__ == '__main__':

View File

@ -39,6 +39,14 @@ class Paste:
f"fetched={self.fetched})" 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: class PastebinAPI:
""" """
@ -142,3 +150,27 @@ class PastebinAPI:
paste.fetched = True paste.fetched = True
return paste 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()]