diff --git a/src/fares_site/api_calling.py b/src/fares_site/api_calling.py index cb809ec..90c0384 100644 --- a/src/fares_site/api_calling.py +++ b/src/fares_site/api_calling.py @@ -5,20 +5,46 @@ Standard functions to call for fares information. # Imports import requests import pandas as pd -import numpy as np +from os import environ +import json + # Init. +COLUMN_RENAMES = { + "origin_code": "Origin", + "destination_code": "Destination", + "route_code": "Route", + "status_code": "Status", + "usage_code": "Usage", + "direction": "Direction", + "end_date": "Ends", + "start_date": "Starts", + "toc": "TOC", + "cross_london_flag": "Cross London", + "settlement_flag": "Settlement", + "discount_flag": "Discount", + "flow_id": "ID", + "ticket_code": "Ticket Code", + "fare": "Fare", + "restriction_code": "Restriction", +} # Functions -def fares_query(origin: str, dest: str, date: str) -> pd.DataFrame: - _ = requests # .get(url=url, headers=headers) - df = pd.DataFrame( - { - "origin": [origin for _ in range(10)], - "dest": [dest for _ in range(10)], - "date": [date for _ in range(10)], - "fare": np.random.rand(10) * 20, - } +def fares_query(origin: str, destination: str) -> pd.DataFrame: + response = requests.get( + url=f"https://fares.ballast-data.co.uk/fares?origin={origin}&destination={destination}", + auth=( + environ.get("BD_FARES_USER", ""), + environ.get("BD_FARES_PASS", ""), + ), ) - return df + dfs, data = [], json.loads(response.content.decode()) + for flow_fares in data: + df = pd.json_normalize(flow_fares["fares"]).drop("flow_id", axis=1) + meta = pd.DataFrame.from_records( + [flow_fares["flow_id"] | {"Number": number} for number in df.index] + ).rename(COLUMN_RENAMES, axis=1) + df.index = pd.MultiIndex.from_frame(meta) + dfs.append(df) + return pd.concat(dfs).rename(COLUMN_RENAMES, axis=1) diff --git a/src/fares_site/serve.py b/src/fares_site/serve.py index f73d358..17f8d6e 100644 --- a/src/fares_site/serve.py +++ b/src/fares_site/serve.py @@ -19,12 +19,13 @@ HTML_CONTENT_HEADER = """
- - + + + - -