-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPyCurrency.py
More file actions
130 lines (95 loc) · 3.09 KB
/
PyCurrency.py
File metadata and controls
130 lines (95 loc) · 3.09 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
119
120
121
122
123
124
125
126
127
128
129
130
import urllib2, json, time, glob, os
class PyCurrency:
# Constructor
def __init__(self, cachable = True, cacheFolder = 'cache', cacheTimeout = 3600):
if not os.access(cacheFolder, os.F_OK):
cachable = False
self.cachable = False
if cachable:
self.cachable = True
self.cacheFolder = cacheFolder
self.cacheTimeout = 3600
# Performs conversion
def convert(self, amount, fromCurrency, toCurrency, rounded = False):
amount = float(amount)
if self.validateCurrency([fromCurrency, toCurrency]) is False:
raise NameError('Invalid currency code!')
# Get rate
rate = self.getRate(fromCurrency, toCurrency)
converted = rate * amount
if rounded:
return round(float(converted), 2)
else:
return converted
# Calculates amount needed in currency to achieve finish currency
def amountTo(self, finalAmount, fromCurrency, toCurrency, rounded = False):
finalAmount = float(finalAmount)
if finalAmount == 0:
return 0
if self.validateCurrency([fromCurrency, toCurrency]) is False:
raise NameError('Invalid currency code!')
rate = self.getRate(fromCurrency, toCurrency)
amount = finalAmount / float(rate)
if rounded:
return round(amount, 2)
else:
return amount
# Returns the rate
def getRate(self, fromCurrency, toCurrency):
rate = self.getCache(fromCurrency + toCurrency)
if not rate:
fetch = self.fetch(1, fromCurrency, toCurrency)
rate = fetch['rate']
# Cache this rate
self.newCache(fromCurrency.upper() + toCurrency.upper(), rate)
return float(rate)
# Fetches data from API
def fetch(self, amount, fromCurrency, toCurrency):
URL = 'http://rate-exchange.appspot.com/currency?q=' + str(amount) + \
'&from=' + fromCurrency + '&to=' + toCurrency
response = urllib2.urlopen(URL)
data = json.load(response)
return data
# Checks if rate is cached and returns rate
# Will return False if cache does not exist our data is timedout
#
# fileName should be currencies concat'd
def getCache(self, fileName):
if self.cachable is not True:
return False
path = os.path.join(self.cacheFolder, fileName + '.convertcache')
# Check if file exists
try:
with open(path): pass
except IOError:
return False
# Array of lines
f = open(path).readlines()
# Check if cache is too old
if float(f[0]) < (time.time() - self.cacheTimeout):
return False
# Return the rate
return f[1]
# Validates the currency codes
# Argument should be an array of the code(s)
def validateCurrency(self, codes):
for code in codes:
if len(code) != 3 or code.isalnum() is False:
if code.upper() != 'BEAC':
return False
return True
# Makes a new cache file
# fileName should be currency codes in caps, FROMTO (i.e. GBPUSD)
def newCache(self, fileName, rate):
if self.cachable:
data = str(time.time()) + '\n' + str(rate)
path = os.path.join(self.cacheFolder, fileName.upper() + '.convertcache')
f = open(path, 'w')
f.write(data)
f.close()
# Deletes all cached files
def clearCache(self):
os.chdir(self.cacheFolder)
fileList = glob.glob('*.convertcache')
for cache in fileList:
os.remove(cache)