1 |
james |
12 |
# > !Currency.py.Rates/py |
2 |
|
|
|
3 |
|
|
import pickle |
4 |
|
|
import string |
5 |
james |
52 |
import time |
6 |
james |
12 |
import urllib |
7 |
|
|
|
8 |
|
|
|
9 |
|
|
def load(cache): |
10 |
|
|
global _date, _rates |
11 |
|
|
c = open(cache, 'r') |
12 |
|
|
_date = pickle.load(c) |
13 |
|
|
_rates = pickle.load(c) |
14 |
|
|
c.close() |
15 |
|
|
|
16 |
|
|
|
17 |
|
|
def update(url, cache, us, dollar): |
18 |
|
|
global _date, _rates |
19 |
|
|
rates = [(us, dollar, 1.0)] |
20 |
|
|
u = urllib.urlopen(url) |
21 |
|
|
c = open(cache, 'w') |
22 |
james |
52 |
_date = time.strftime('%d %b %Y') |
23 |
james |
12 |
while 1: |
24 |
|
|
l = u.readline() |
25 |
james |
52 |
if l == '': |
26 |
james |
12 |
break |
27 |
james |
52 |
l = l[:-1] |
28 |
|
|
m = string.split(l, ' ', 1) |
29 |
|
|
rates.append(('', m[1], eval(m[0]))) |
30 |
james |
12 |
u.close() |
31 |
|
|
pickle.dump(_date, c, 1) |
32 |
|
|
_rates = rates |
33 |
|
|
pickle.dump(_rates, c, 1) |
34 |
|
|
c.close() |
35 |
|
|
|
36 |
|
|
|
37 |
|
|
def currencies(format): |
38 |
|
|
return map(lambda rate, format = format: |
39 |
|
|
format % {'country': rate[0], 'currency': rate[1], 'rate': rate[2]}, |
40 |
|
|
_rates) |
41 |
|
|
|
42 |
|
|
|
43 |
|
|
def currency(format, i): |
44 |
|
|
return format % {'country': _rates[i][0], 'currency': _rates[i][1], 'rate': _rates[i][2]} |
45 |
|
|
|
46 |
|
|
|
47 |
|
|
def date(): |
48 |
|
|
return _date |
49 |
|
|
|
50 |
|
|
|
51 |
|
|
def convert(currency, value): |
52 |
|
|
conversion = [] |
53 |
|
|
base = float(value) / _rates[currency][2] |
54 |
|
|
for rate in _rates: |
55 |
|
|
conversion.append(base * rate[2]) |
56 |
|
|
return conversion |