-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.py
executable file
·119 lines (88 loc) · 2.96 KB
/
calculator.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
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
#!/usr/bin/env python2.7
import re
import uuid
from flask import Flask, jsonify, render_template, request, session
import numpy as np
class Calculator(object):
def __init__(self):
self.all_results = {}
@staticmethod
def _to_number(number_str):
try:
return int(number_str)
except ValueError:
try:
return float(number_str)
except ValueError as e:
raise e
def calculate(self, sess_id, arg1_str, arg2_str, op):
if sess_id not in self.all_results:
self.all_results[sess_id] = []
curr_results = self.all_results[sess_id]
# Caller will catch ValueErrors raised by this
arg1 = self._to_number(arg1_str)
arg2 = self._to_number(arg2_str)
if op == "+":
calc_result = arg1 + arg2
elif op == "-":
calc_result = arg1 - arg2
elif op == "*":
calc_result = arg1 * arg2
elif op == "/":
calc_result = float(arg1) / float(arg2)
else:
raise ValueError("Allowed operators are +, -, * and /")
result = "{} {} {} = {}".format(arg1, op, arg2, calc_result)
curr_results.append(result)
return calc_result
def calculate_and_get_sin(self, arg):
arg = float(arg)
return np.sin(arg)
def get_results(self, sess_id):
if sess_id not in self.all_results:
self.all_results[sess_id] = []
return self.all_results[sess_id]
app = Flask(__name__)
app.debug = True
app.secret_key = "topsecret"
calculator = Calculator()
@app.route("/sin.json")
def get_sin():
errors = []
try:
arg = request.args["arg"]
sin_res = calculator.calculate_and_get_sin(arg)
return jsonify(sinRes=sin_res, errors=errors)
except KeyError as e:
errors.append(unicode(e))
return jsonify(errors=errors)
except ValueError as e:
errors.append(unicode(e))
return jsonify(errors=errors)
@app.route("/calculations.json")
def get_calculations_ajax():
if "id" not in session:
session["id"] = unicode(uuid.uuid4())
return jsonify(results=calculator.get_results(session["id"]))
@app.route("/do_calculation.json")
def do_calculate_ajax():
errors = []
if "id" not in session:
session["id"] = unicode(uuid.uuid4())
try:
arg1 = request.args["arg1"]
arg2 = request.args["arg2"]
op = request.args["op"]
calc_result = calculator.calculate(session["id"], arg1, arg2, op)
except KeyError as e:
errors.append(unicode(e))
except ValueError as e:
# We got some invalid values from the user who should be informed in
# returned page.
errors.append(unicode(e))
return jsonify(calcResult=calc_result, errors=errors)
@app.route("/")
def calculator_page():
return render_template("calculator.html")
if __name__ == "__main__":
app.run(host="0.0.0.0")