Last active
June 7, 2022 14:48
-
-
Save bbelderbos/00a46e717993de277ed4e6081d102def to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from rich.console import Console | |
from rich.table import Table | |
ARTICLES_API = "https://codechalleng.es/api/articles/" | |
TABLE_TITLE = "Matching Pybites Articles" | |
COLUMNS = ("title", "link", "author", "publish_date", "tags") | |
COLORS = ("#ff6e4a", "#00bfff", "magenta", "cyan", "#5f87d7") | |
console = Console() | |
error_console = Console(stderr=True, style="bold red") | |
class ArticleSearcher: | |
def __init__(self): | |
self.articles = self._load_feed() | |
@staticmethod | |
def _load_feed(): | |
resp = requests.get(ARTICLES_API) | |
resp.raise_for_status() | |
return resp.json() | |
def search_articles(self, term): | |
term = term.lower() | |
for article in self.articles: | |
all_fields = "".join(article.values()).lower() | |
if term in all_fields: | |
yield article | |
@staticmethod | |
def create_table(matches): | |
table = Table(title=TABLE_TITLE) | |
for column, color in zip(COLUMNS, COLORS): | |
table.add_column(column, style=color) | |
for m in matches: | |
values = list(m.values()) | |
values.pop(4) # hide summary to save space | |
table.add_row(*values) | |
return table | |
def __call__(self): | |
while True: | |
term = input("Search articles ('q' to exit): ") | |
if term == "q": | |
console.print("Bye") | |
break | |
if not term.strip(): | |
error_console.print("Please enter search term") | |
continue | |
matches = self.search_articles(term) | |
table = self.create_table(matches) | |
console.print(table) | |
if __name__ == "__main__": | |
ArticleSearcher()() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment