Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added __pycache__/tests.cpython-38.pyc
Binary file not shown.
78 changes: 71 additions & 7 deletions calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,45 @@

"""

import traceback

def home():
page = """
<h1>WSGI Calculator Paths</h1>
<table>
<tr><th>Addition: add/number/number</td></tr>
<tr><th>Subtraction: subtract/number/number</td></tr>
<tr><th>Multiplication: multiply/number/number</td></tr>
<tr><th>Division: divide/number/number</td></tr>
</table>
"""
return page

def add(*args):
""" Returns a STRING with the sum of the arguments """

# TODO: Fill sum with the correct value, based on the
# args provided.
sum = "0"

return sum
total = str(int(args[0]) + int(args[1]))
return total

# TODO: Add functions for handling more arithmetic operations.

def subtract(*args):
total = str(int(args[0]) - int(args[1]))
return total


def multiply(*args):
total = str(int(args[0]) * int(args[1]))
return total


def divide(*args):
total = str(int(args[0]) / int(args[1]))
return total


def resolve_path(path):
"""
Should return two values: a callable and an iterable of
Expand All @@ -63,11 +90,27 @@ def resolve_path(path):
# examples provide the correct *syntax*, but you should
# determine the actual values of func and args using the
# path.
func = add
args = ['25', '32']
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, args


def application(environ, start_response):
# TODO: Your application code from the book database
# work here as well! Remember that your application must
Expand All @@ -76,9 +119,30 @@ def application(environ, start_response):
#
# TODO (bonus): Add error handling for a user attempting
# to divide by zero.
pass
headers = [("Content-type", "text/html")]
try:
path = environ.get('PATH_INFO', None)
if path is None:
raise NameError
func, args = resolve_path(path)
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__':
# TODO: Insert the same boilerplate wsgiref simple
# server creation that you used in the book database.
pass
from wsgiref.simple_server import make_server
srv = make_server('localhost', 8080, application)
srv.serve_forever()