-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathcalculator.py
More file actions
103 lines (83 loc) · 2.42 KB
/
calculator.py
File metadata and controls
103 lines (83 loc) · 2.42 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
import traceback
from templates import Template
def home():
return Template.home()
def add(*args):
try:
sum = 0
for i in range(0, len(args)):
sum = sum + int(args[i])
except ValueError:
return "This application requires integer values."
return str(sum)
def subtract(*args):
try:
diff = int(args[0])
for i in range(1, len(args)):
diff = diff - int(args[i])
except ValueError:
return "This application requires integer values."
return str(diff)
def multiply(*args):
try:
multiple = 1
for i in range(0, len(args)):
multiple = multiple * int(args[i])
except ValueError:
return "This application requires integer values."
return str(multiple)
def divide(*args):
try:
div = int(args[0])
for i in range(1, len(args)):
div = div / int(args[i])
except ValueError:
return "This application requires integer values."
except ZeroDivisionError:
return "Cannot divide by zero."
return str(div)
def resolve_path(path):
"""
Should return two values: a callable and an iterable of
arguments.
"""
funcs = {
'': home,
'add': add,
'subtract': subtract,
'multiply': multiply,
'divide': divide,
}
path = path.strip('/').split('/')
func_name = path[0]
args = path[1:]
try:
func = funcs[func_name]
except KeyError:
raise NameError
return func_name, func, args
def application(environ, start_response):
headers = [('Content-type', 'text/html')]
try:
path = environ.get('PATH_INFO', None)
if path is None:
raise NameError
func_name, func, args = resolve_path(path)
body = Template.answer(func_name, func(*args))
body = func(*args)
status = "200 OK"
except NameError:
status = "404 Not Found"
body = '<h1>Not Found</h1>'
except Exception:
status = '500 Internal Server Error'
body = '<h1>Internal Server Error</h1>'
print(traceback.format_exc())
finally:
headers.append(('Content-length', str(len(body))))
start_response(status, headers)
return [body.encode('utf8')]
if __name__ == '__main__':
from wsgiref.simple_server import make_server
srv = make_server('localhost', 8080, application)
srv.serve_forever()