-
Notifications
You must be signed in to change notification settings - Fork 0
/
currency.py
47 lines (44 loc) · 1.88 KB
/
currency.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
47
import pycurl
import certifi
import re
from io import BytesIO
#https://github.com/fawazahmed0/currency-api#readme
def getURLData(URL):
#stolen shamelessly from the pycurl documentation site. http://pycurl.io/docs/latest/quickstart.html and edited a little for my own ends.
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, URL)
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.CAINFO, certifi.where())
c.perform()
c.close()
body = buffer.getvalue()
# Body is a byte string.
# We have to know the encoding in order to print it to a text file
# such as standard output.
body=body.decode('iso-8859-1')
return body
def findSecondCurrencyCode(URLjson,secondCurrecyCode):
for line in URLjson.split("\n"):
line=re.search(secondCurrecyCode+r'.*', URLjson)
return line.group()
def main():
exchangeDate=input("Enter a date in (yyyy-mm-dd) format. leave blank for latest data: ")
if exchangeDate=="":
exchangeDate="latest"
firstCurrencyCode=input("Enter first currency shortcode(eg:usd,gbp,cad): ")
currencyAmount=input("Enter the amount of currency to convert: ")
secondCurrecyCode=input("Enter second currency shortcode: ")
if(firstCurrencyCode==secondCurrecyCode):
print(f"{currencyAmount} {firstCurrencyCode} is worth {currencyAmount} {secondCurrecyCode}")
exit()
finalURL= f"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/{exchangeDate}/currencies/{firstCurrencyCode}.json"
URLjson=getURLData(finalURL)
URLjson= re.sub(r',', "", URLjson)
line=findSecondCurrencyCode(URLjson,secondCurrecyCode)
line=re.sub(r'.+:\W', "", line)
convertedCurrency=float(line)*int(currencyAmount)
convertedCurrency=round(convertedCurrency,2)
print(f"at {exchangeDate} {currencyAmount} {firstCurrencyCode} is worth {convertedCurrency} {secondCurrecyCode}")
if __name__=="__main__":
main()