Skip to content

Finished assignment for lesson04 #19

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 4 commits into
base: master
Choose a base branch
from
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
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ Your assignment is to create a WSGI calculator that you can use to add, subtract

You'll use the calculator by visiting an address like: [http://localhost:8080/multiply/3/5](http://localhost:8080/multiply/3/5). Once you've completed the assignment, if you were to run the program and visit this page then you would expect to see a page in your browser with the text "15".

You'll also have to create one more page: an index page at the address http://localhost:8080/ with some text instructions that explain (in just a few sentences) how to use the site.
You'll also have to create one more page: an index page at the address [http://localhost:8080/](http://localhost:8080/) with some text instructions that explain (in just a few sentences) how to use the site.

## How to Know When You're Done

When you have completed the TODOs, you should be able to visit the following pages and see a page with the indicated content.:
* http://localhost:8080/multiply/3/5  => 15
* http://localhost:8080/add/23/42  => 65
* http://localhost:8080/subtract/23/42  => -19
* http://localhost:8080/divide/22/11  => 2
* http://localhost:8080/  => Here's how to use this page... (etc.)
* [httpL//localhost:8080/add/3/5](http://localhost:8080/multiply/3/5)  => 15
* [http://localhost:8080/add/23/42](http://localhost:8080/add/23/42)  => 65
* [http://localhost:8080/subtract/23/42](http://localhost:8080/subtract/23/42)  => -19
* [http://localhost:8080/divide/22/11](http://localhost:8080/divide/22/11)  => 2
* [http://localhost:8080/](http://localhost:8080/)  => Here's how to use this page... (etc.)

There is also a set of tests for you to run, using `python tests.py`.
106 changes: 94 additions & 12 deletions calculator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import re
import traceback

"""
For your homework this week, you'll be creating a wsgi application of
your own.
Expand Down Expand Up @@ -44,14 +47,50 @@

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

# TODO: Add functions for handling more arithmetic operations.
try:
res = str(int(args[0]) + int(args[1]))
return '{} + {} = {}'.format(args[0], args[1], res)
except ValueError:
raise ValueError

def substract(*args):
""" Returns a STRING with the subtract of the arguments """
try:
res = str(int(args[0]) - int(args[1]))
return '{} - {} = {}'.format(args[0], args[1], res)
except ValueError:
raise ValueError

def multiply(*args):
""" Returns a STRING with the multiply of the arguments """
try:
res = str(int(args[0]) * int(args[1]))
return '{} * {} = {}'.format(args[0], args[1], res)
except ValueError:
raise ValueError

def divide(*args):
""" Returns a STRING with the divide of the arguments """
try:
res = str(int(args[0]) / int(args[1]))
return '{} / {} = {}'.format(args[0], args[1], res)
except ValueError:
if args[1] == 0:
raise ZeroDivisionError
raise ValueError

def instructions():
""" Returns a STRING about how to use the calculator """
ins = """
<h1> Here is how to use the calculator:</h1>
<li> Input URL http://localhoat:8080/add/2/3 for 2 + 3</li>
<li> Input URL http://localhoat:8080/multiply/2/3 for 2 * 3</li>
<li> Input URL http://localhoat:8080/subtract/2/3 for 2 - 3</li>
<li> Input URL http://localhoat:8080/divide/2/3 for 2 / 3</li>
"""
return ins

def resolve_path(path):
"""
Expand All @@ -63,10 +102,23 @@ 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']

return func, args
functions = {
'': instructions,
'add': add,
'subtract': substract,
'multiply': multiply,
'divide': divide
}
path = path.strip('/').split('/')
func_name = path[0]
func_args = path[1:]

try:
func = functions[func_name]
except KeyError:
raise NameError
finally:
return func, func_args

def application(environ, start_response):
# TODO: Your application code from the book database
Expand All @@ -76,9 +128,39 @@ 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)
#if len(args) == 1 or len(args) > 2:
# raise ValueError
body = func(*args)
status = '200 OK'
except ValueError:
status = '500 Internal Server Error'
body = '<h1>Unable to finish the calculation. Please provide two numbers.</h1>'
except NameError:
status = '404 Not Found'
body = '<h1>404 Operation Method Not Found</h1>'
except ZeroDivisionError:
status = '500 Internal Server Error'
body = '<h1>Zero Division Error!</h1>'
except Exception:
status = '500 Internal Server Error'
body = '<h1>Internal Server Error </h1>'
print(traceback.format_exc())
finally:
headers.append(('Content-len', 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('127.0.0.1', 8080, application)
#srv = make_server('localhost', 8080, application)
srv.serve_forever()