|
| 1 | +""" |
| 2 | +CAUTION: You may get a json.decoding error. This works for some of us but fails for others. |
| 3 | +""" |
| 4 | + |
| 5 | +from datetime import datetime |
| 6 | + |
| 7 | +import requests |
| 8 | +from rich import box |
| 9 | +from rich import console as rich_console |
| 10 | +from rich import table as rich_table |
| 11 | + |
| 12 | +LIMIT = 10 |
| 13 | +TODAY = datetime.now() |
| 14 | + |
| 15 | +API_URL = ( |
| 16 | + "https://www.forbes.com/forbesapi/person/rtb/0/position/true.json" |
| 17 | + "?fields=personName,gender,source,countryOfCitizenship,birthDate,finalWorth" |
| 18 | + f"&limit={LIMIT}" |
| 19 | +) |
| 20 | + |
| 21 | + |
| 22 | +def calculate_age(unix_date: int) -> str: |
| 23 | + """Calculates age from given unix time format. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + Age as string |
| 27 | +
|
| 28 | + >>> calculate_age(-657244800000) |
| 29 | + '73' |
| 30 | + >>> calculate_age(46915200000) |
| 31 | + '51' |
| 32 | + """ |
| 33 | + birthdate = datetime.fromtimestamp(unix_date / 1000).date() |
| 34 | + return str( |
| 35 | + TODAY.year |
| 36 | + - birthdate.year |
| 37 | + - ((TODAY.month, TODAY.day) < (birthdate.month, birthdate.day)) |
| 38 | + ) |
| 39 | + |
| 40 | + |
| 41 | +def get_forbes_real_time_billionaires() -> list[dict[str, str]]: |
| 42 | + """Get top 10 realtime billionaires using forbes API. |
| 43 | +
|
| 44 | + Returns: |
| 45 | + List of top 10 realtime billionaires data. |
| 46 | + """ |
| 47 | + response_json = requests.get(API_URL).json() |
| 48 | + return [ |
| 49 | + { |
| 50 | + "Name": person["personName"], |
| 51 | + "Source": person["source"], |
| 52 | + "Country": person["countryOfCitizenship"], |
| 53 | + "Gender": person["gender"], |
| 54 | + "Worth ($)": f"{person['finalWorth'] / 1000:.1f} Billion", |
| 55 | + "Age": calculate_age(person["birthDate"]), |
| 56 | + } |
| 57 | + for person in response_json["personList"]["personsLists"] |
| 58 | + ] |
| 59 | + |
| 60 | + |
| 61 | +def display_billionaires(forbes_billionaires: list[dict[str, str]]) -> None: |
| 62 | + """Display Forbes real time billionaires in a rich table. |
| 63 | +
|
| 64 | + Args: |
| 65 | + forbes_billionaires (list): Forbes top 10 real time billionaires |
| 66 | + """ |
| 67 | + |
| 68 | + table = rich_table.Table( |
| 69 | + title=f"Forbes Top {LIMIT} Real Time Billionaires at {TODAY:%Y-%m-%d %H:%M}", |
| 70 | + style="green", |
| 71 | + highlight=True, |
| 72 | + box=box.SQUARE, |
| 73 | + ) |
| 74 | + for key in forbes_billionaires[0]: |
| 75 | + table.add_column(key) |
| 76 | + |
| 77 | + for billionaire in forbes_billionaires: |
| 78 | + table.add_row(*billionaire.values()) |
| 79 | + |
| 80 | + rich_console.Console().print(table) |
| 81 | + |
| 82 | + |
| 83 | +if __name__ == "__main__": |
| 84 | + display_billionaires(get_forbes_real_time_billionaires()) |
0 commit comments