/
app.py
71 lines (53 loc) · 1.58 KB
/
app.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
import sys
import urllib2
API = 'https://free.currencyconverterapi.com/api/v6/convert?q={}&compact=y'
CURRENCIES = {}
with open('currencies.json') as f:
# This is the content of request
# https://free.currencyconverterapi.com/api/v6/currencies
CURRENCIES = json.loads(f.read())['results']
def fetch_currency_factor(from_, to):
key = '{}_{}'.format(from_, to).upper()
url = API.format(key)
try:
response = urllib2.urlopen(url).read()
data = json.loads(response)
return data[key]['val']
except Exception:
return None
def parse_input(raw_str):
regex = re.compile(r'(\d+)\ (\w+)\ to\ (\w+)')
result = regex.search(query.strip().lower())
if result:
return result.groups()
else:
return None
def prepare_output(value, key):
currency = CURRENCIES[key.upper()]
title = '{} {}'.format(currency['currencySymbol'], str(value))
return {
'uid': currency['id'],
'title': title,
'subtitle': currency['currencyName'],
'type': 'default',
'icon': {
'path': './icons/{}.png'.format(key.lower()),
},
'arg': value,
}
final_result = {
'items': [],
}
query = ' '.join(sys.argv[1:])
result = parse_input(query)
if result:
(value, from_, to) = result
factor = fetch_currency_factor(from_, to)
if factor:
res = float(value) * factor
final_result['items'].append(prepare_output(res, to))
sys.stdout.write(json.dumps(final_result))