-
Notifications
You must be signed in to change notification settings - Fork 1
/
eur
executable file
·103 lines (85 loc) · 2.99 KB
/
eur
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
#!/usr/bin/env python3
'''eur to uah and oppsote convertor using PrivatBank API'''
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import json
import datetime
import requests
def main():
'''Define the mode'''
if len(sys.argv) == 1:
interactive()
else:
autoconvert()
def get_rates():
'''Download rates from API'''
cache = "/tmp/currency_rates.cache"
if os.path.isfile(cache):
dt = os.path.getmtime(cache)
if os.path.isfile(cache) and (datetime.datetime.utcfromtimestamp(dt) > datetime.datetime.utcnow() - datetime.timedelta(minutes=10)):
with open(cache, 'r') as file:
data = json.load(file)
else:
try:
resp = requests.get(
"https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5")
data = resp.json()
with open(cache, 'w') as file:
json.dump(data, file)
except:
if os.path.isfile(cache):
with open(cache, 'r') as file:
print(
"Attention! PrivatBank API is not available, using cached values.")
data = json.load(file)
else:
sys.exit(
"PrivatBank API is not available and no cache found. Exiting...")
return (data)
def autoconvert():
'''Parse arguments'''
parser = argparse.ArgumentParser(
description='UAH<>EUR converter using PrivatBank API. Can be used either in interactive mode (without arguments) or in automatic mode (exactly two arguments required).')
parser.add_argument('amount', metavar='N', type=float,
help='amount of currency to convert')
parser.add_argument('curr', metavar='C', type=str,
help='currency to convert from')
args = parser.parse_args()
# Get rates
data = get_rates()
# Convert
if args.curr in ("eur", "EUR"):
print("%.2f UAH" % (args.amount*float(data[1]["buy"])))
elif args.curr in ("uah", "UAH"):
print("%.2f UAD" % (args.amount/float(data[1]["sale"])))
else:
print("Allowed currencies: UAH|EUR")
def interactive():
'''Get and print rates'''
data = get_rates()
course = round(float(data[0]["buy"]), 2)
print("EUR buying rate for ", datetime.date.today(), ":", course, ' UAH')
# Start interactive mode
def _is_number(string):
try:
float(string)
return True
except ValueError:
return False
print("1. EUR --> UAH")
print("2. UAH --> EUR")
response = None
while response not in ('1', '2'):
response = input('Choose direction: ')
sum_value = ''
while _is_number(sum_value) == False:
sum_value = input('Enter the sum to exchange: ')
# print sum_value
if response == '1':
print("%.2f UAH" % (float(sum_value) * course))
elif response == '2':
print("%.2f EUR" % (float(sum_value) / course))
if __name__ == "__main__":
main()