72 lines
2.4 KiB
Python
72 lines
2.4 KiB
Python
"""Print classic mini-league standings, including optional pagination."""
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from urllib.error import URLError
|
|
from urllib.request import Request, urlopen
|
|
|
|
BASE_URL = "https://fantasy.premierleague.com/api/"
|
|
|
|
|
|
def get_json(path):
|
|
"""Send an HTTP GET request and turn the JSON response into a Python dict."""
|
|
request = Request(
|
|
BASE_URL + path,
|
|
headers={"User-Agent": "FPL-API-Demo/1.0", "Accept": "application/json"},
|
|
)
|
|
with urlopen(request, timeout=20) as response:
|
|
return json.load(response)
|
|
|
|
|
|
def positive_int(value):
|
|
number = int(value)
|
|
if number < 1:
|
|
raise argparse.ArgumentTypeError("must be a positive integer")
|
|
return number
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--league-id", type=positive_int, default=37803)
|
|
parser.add_argument("--page", type=positive_int, default=1)
|
|
parser.add_argument(
|
|
"--all-pages", action="store_true", help="fetch all pages from --page onwards"
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
page = args.page
|
|
while True:
|
|
# This example uses classic scoring; head-to-head leagues use other endpoints.
|
|
data = get_json(
|
|
f"leagues-classic/{args.league_id}/standings/?page_standings={page}"
|
|
)
|
|
if page == args.page:
|
|
print(f"League: {data['league']['name']} (ID {args.league_id})")
|
|
print(f"\nPage {page}")
|
|
print(f"{'Rank':<6} {'Team':<30} {'Manager':<26} {'GW':>5} {'Total':>7} {'Entry ID':>10}")
|
|
standings = data["standings"]
|
|
for entry in standings["results"]:
|
|
print(
|
|
f"{entry['rank']:<6} {entry['entry_name']:<30} "
|
|
f"{entry['player_name']:<26} {entry['event_total']:>5} "
|
|
f"{entry['total']:>7} {entry['entry']:>10}"
|
|
)
|
|
if not standings["results"]:
|
|
print("No ranked entries on this page.")
|
|
if not standings["has_next"]:
|
|
break
|
|
if not args.all_pages:
|
|
print(f"\nMore results available: use --page {page + 1} or --all-pages.")
|
|
break
|
|
page += 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (URLError, TimeoutError, OSError, ValueError, KeyError) as exc:
|
|
print(f"Unable to load league data: {exc}", file=sys.stderr)
|
|
print("Check the classic league ID and connection. The API may also be unavailable.", file=sys.stderr)
|
|
sys.exit(1)
|