-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcurrency_api.py
More file actions
118 lines (94 loc) · 3.75 KB
/
currency_api.py
File metadata and controls
118 lines (94 loc) · 3.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import requests
import configuration as config
currency_data = {}
static_currency_data = {
"SGD": 1.0,
"USD": 0.74,
"EUR": 0.63,
"JPY": 79.0,
"GBP": 0.54,
"AUD": 1.0,
"CAD": 0.94,
}
"""Global cache for currency exchange rates relative to SGD.
Keys are currency codes (str), values are floats representing how many units
of the keyed currency correspond to 1 SGD. Initially populated with examples,
can be updated by `get_currency_rate`.
"""
def get_currency_rate():
"""Fetches or returns cached currency exchange rates relative to SGD.
Attempts to fetch live rates from the RapidAPI endpoint if the global
`currency_data` cache is empty. Updates the cache on success.
Uses `configuration.RAPIDAPI_KEY`.
Returns:
A dictionary mapping currency codes (str) to their exchange rate
relative to SGD (float: units of currency per 1 SGD), or None if
fetching or processing fails.
"""
global currency_data
if currency_data:
return currency_data
elif config.API_ON:
url = "https://booking-com15.p.rapidapi.com/api/v1/meta/getExchangeRates"
querystring = {"base_currency": "SGD"}
headers = {
"x-rapidapi-key": config.RAPIDAPI_KEY,
"x-rapidapi-host": "booking-com15.p.rapidapi.com"
}
try:
response = requests.get(url, headers=headers, params=querystring)
response.raise_for_status()
data = response.json()
for exchange_rate in data["data"]["exchange_rates"]:
currency_data[exchange_rate["currency"]] = float(exchange_rate["exchange_rate_buy"]) # Use exchange_rate_buy
return currency_data
except requests.exceptions.RequestException as e:
print(f"Error fetching currency rates: {e}")
return static_currency_data
except (KeyError, TypeError, ValueError) as e:
print(f"Error processing API response: {e}")
return static_currency_data
else:
return static_currency_data
def get_list_of_currency():
"""Gets the list of available currency codes from the cache.
Calls `get_currency_rate()` to ensure rates are loaded/fetched if needed.
Returns:
A list of currency code strings (e.g., ['SGD', 'USD', 'EUR']),
or an empty list if rates are unavailable.
"""
currency_data = get_currency_rate()
if currency_data:
return list(currency_data.keys())
else:
return []
def convert_currency_from_SGD(amount, to_currency):
"""Converts an amount from SGD to a target currency.
Uses the cached exchange rates.
Args:
amount: The amount in SGD.
to_currency: The currency code (str) to convert to.
Returns:
The equivalent amount in the target currency, rounded to 2 decimal
places, or None if the currency rate is not available.
"""
currency_data = get_currency_rate()
if currency_data and to_currency in currency_data:
return round(amount / currency_data["SGD"] * currency_data[to_currency], 2) # Important change here
else:
return None
def convert_currency_to_SGD(amount, from_currency):
"""Converts an amount from a specified currency to SGD.
Uses the cached exchange rates.
Args:
amount: The amount in the `from_currency`.
from_currency: The currency code (str) to convert from.
Returns:
The equivalent amount in SGD, rounded to 2 decimal places, or None
if the currency rate is not available.
"""
currency_data = get_currency_rate()
if currency_data and from_currency in currency_data:
return round(amount / currency_data[from_currency] * currency_data["SGD"], 2) # important change here.
else:
return None