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():
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__':

View File

@ -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()]