Skip to content

got calculator.py working for lesson4 assignment #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
100 changes: 91 additions & 9 deletions calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
http://localhost:8080/add/23/42 => 65
http://localhost:8080/subtract/23/42 => -19
http://localhost:8080/divide/22/11 => 2
http://localhost:8080/ => <html>Here's how to use this page...</html>
http://localhost:8080/ =>
<html>Here's how to use this page...</html>
```

To submit your homework:
Expand All @@ -47,12 +48,47 @@ def add(*args):

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

return sum
final_sum = str(sum(args))
return final_sum

# TODO: Add functions for handling more arithmetic operations.


def subtract(*args):
difference = args[0]
for x in args[1:]:
difference -= x
return str(difference)


def divide(*args):
quotient = args[0]
for x in args[1:]:
quotient /= x
return str(quotient)


def multiply(*args):
product = 1
for x in args:
product *= x
return str(product)


def instructions():
page = """
<h1>Here's how to Use this Page!</h1>
<h2>This is a basic calculator that can add, subtract, multiply and divide</h2>
<ul><li>You are going to be using the URL to do math!</li>
<li>First input a math operation eg. add. This will look like 'http://localhost:8080/add/'</li>
<li>Next input as many numbers as you would like to do the operation upon, separated by '/'.</li>
<li>Finally press enter to get the result!</li>
<li>A valid URL would look like 'http://localhost:8080/multiply/3/5/6'</li>
</ul>
"""
return page


def resolve_path(path):
"""
Should return two values: a callable and an iterable of
Expand All @@ -63,11 +99,29 @@ 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']

# func = add
# args = ['25', '32']
funcs = {
"add": add,
"divide": divide,
"multiply": multiply,
"subtract": subtract,
"": instructions
}
path = path.strip('/').split('/')
func_name = path[0]
argstrings = path[1:]

try:
func = funcs[func_name]
args = [int(x) for x in argstrings]
except KeyError:
raise NameError
except ValueError:
raise ValueError
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 +130,37 @@ 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)
result = func(*args)
if func.__name__ == 'instructions':
body = result
else:
body = "The result of your request to {} is: {}".format(
func.__name__, result)
status = "200 OK"
except NameError:
status = "404 Not Found"
body = "<h1>Not Found</h1>"
except ValueError:
status = "400 Bad Request"
body = "<h1>Unable to do math on strings</h1>"
except ZeroDivisionError:
status = "400 Bad Request"
body = "<h1>Unable to divide by zero</h1>"
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()