-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconverter.py
46 lines (31 loc) · 1.63 KB
/
converter.py
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
from os import getenv
import requests
import aiohttp
from fastapi import HTTPException
from dotenv import load_dotenv
load_dotenv()
API_KEY = getenv("ALPHAVANTAGE_APIKEY")
def sync_converter(from_currency: str, to_currency: str, value: float):
url = f'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency={from_currency}&to_currency={to_currency}&apikey={API_KEY}'
try:
response = requests.get(url=url)
except Exception as error:
raise HTTPException(status_code=424, detail=error)
data = response.json()
if "Realtime Currency Exchange Rate" not in data:
raise HTTPException(status_code=422, detail='Realtime Currency Exchange Rate is missing.')
exchange_rate = float(data['Realtime Currency Exchange Rate']['5. Exchange Rate'])
return value * exchange_rate
async def async_converter(from_currency: str, to_currency: str, value: float):
url = f"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency={from_currency}&to_currency={to_currency}&apikey={API_KEY}"
try:
async with aiohttp.ClientSession() as session:
async with session.get(url=url) as response:
data = await response.json()
except Exception as error:
raise HTTPException(status_code=424, detail=error)
if "Realtime Currency Exchange Rate" not in data:
print(f"API Response: {data}")
raise HTTPException(status_code=422, detail='Realtime Currency Exchange Rate is missing.')
exchange_rate = float(data['Realtime Currency Exchange Rate']['5. Exchange Rate'])
return {to_currency: value * exchange_rate}