From 62604ad9019634549db5c184b581728ebecf5176 Mon Sep 17 00:00:00 2001 From: Sue Lim Date: Wed, 11 Jun 2025 16:30:06 +0800 Subject: [PATCH 1/2] Converter.py refactored to contain currency converter logic only --- Currency Script/src/converter.py | 57 +++++++++++++++----------------- 1 file changed, 26 insertions(+), 31 deletions(-) diff --git a/Currency Script/src/converter.py b/Currency Script/src/converter.py index fbcc0274..5d1a74e1 100644 --- a/Currency Script/src/converter.py +++ b/Currency Script/src/converter.py @@ -1,39 +1,34 @@ -# TODO REVIEW AND ENSURE THE PURPOSE OF THIS MODULE IS TO CONVERT -# Python program to convert the currency -# of one country to that of another country +from api_handler import get_exchange_data -# Import the modules needed -import requests - -class Currency_convertor: - # empty dict to store the conversion rates - rates = {} - - def __init__(self, url): - data = requests.get(url).json() - # Extracting only the rates from the json data +class CurrencyConverter: + def __init__(self): + data = get_exchange_data() self.rates = data["rates"] - # function to do a simple cross multiplication between - # the amount and the conversion rates - def convert(self, from_currency, to_currency, amount): - initial_amount = amount - if from_currency != 'EUR': - amount = amount / self.rates[from_currency] + def convert(self, from_currency: str, to_currency: str, amount: float) -> float: + from_currency = from_currency.upper() + to_currency = to_currency.upper() + + if from_currency not in self.rates or to_currency not in self.rates: + raise ValueError("Invalid currency code.") - # limiting the precision to 2 decimal places - amount = round(amount * self.rates[to_currency], 2) - print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency)) + # Convert amount to base (EUR), then to target + amount_in_base = amount if from_currency == "EUR" else amount / self.rates[from_currency] + converted_amount = round(amount_in_base * self.rates[to_currency], 2) + return converted_amount -# Driver code +# --- DEBUG / MANUAL TEST SECTION --- if __name__ == "__main__": + print("Running manual test for CurrencyConverter...\n") - YOUR_ACCESS_KEY = 'YOUR_ACCESS_KEY_HERE' # Define your access key - url = f'http://data.fixer.io/api/latest?access_key={YOUR_ACCESS_KEY}' # Use f-string for cleaner concatenation - c = Currency_convertor(url) - - from_country = input("From Country (currency code): ") - to_country = input("To Country (currency code): ") - amount = float(input("Amount: ")) # Use float for decimal support + converter = CurrencyConverter() + from_cur = "USD" + to_cur = "AUD" + amt = 100.0 - c.convert(from_country, to_country, amount) + print(f"Converting {amt} {from_cur} to {to_cur}...") + try: + result = converter.convert(from_cur, to_cur, amt) + print(f"{amt} {from_cur} = {result} {to_cur}") + except ValueError as e: + print("Error during conversion:", e) \ No newline at end of file From a0451f799612562202a266e7d513234623fd4599 Mon Sep 17 00:00:00 2001 From: Sue Lim Date: Wed, 11 Jun 2025 16:31:26 +0800 Subject: [PATCH 2/2] Updated API Link --- Currency Script/src/api_handler.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Currency Script/src/api_handler.py b/Currency Script/src/api_handler.py index 226c88d8..6f3ed23a 100644 --- a/Currency Script/src/api_handler.py +++ b/Currency Script/src/api_handler.py @@ -1,18 +1,21 @@ import requests -import json -def get_exchange_data(api_url: str = "https://theratesapi.com/api/latest/") -> dict: +def get_exchange_data(api_url: str = "https://open.er-api.com/v6/latest") -> dict: """Fetch latest exchange data from the API.""" response = requests.get(api_url) if response.status_code != 200: raise Exception(f"API request failed with status {response.status_code}") data = response.json() - return data # This includes 'base', 'date', and 'rates' + # Ensure response was successful + if data.get("result") != "success": + raise Exception(f"API returned error: {data.get('error-type', 'Unknown error')}") + + return data # Includes 'base_code', 'time_last_update_utc', and 'rates' # NOTE - for logging & debugging if __name__ == "__main__": exchange_data = get_exchange_data() - print("Base currency:", exchange_data["base"]) - print("Date:", exchange_data["date"]) + print("Base currency:", exchange_data["base_code"]) + print("Date:", exchange_data["time_last_update_utc"]) print("Rates:", list(exchange_data["rates"].items())[:5])