Skip to content
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

completed #5

Open
wants to merge 1 commit 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
Binary file added __pycache__/templates.cpython-36.pyc
Binary file not shown.
155 changes: 87 additions & 68 deletions calculator.py
Original file line number Diff line number Diff line change
@@ -1,84 +1,103 @@
"""
For your homework this week, you'll be creating a wsgi application of
your own.

You'll create an online calculator that can perform several operations.
import traceback
from templates import Template

You'll need to support:

* Addition
* Subtractions
* Multiplication
* Division

Your users should be able to send appropriate requests and get back
proper responses. For example, if I open a browser to your wsgi
application at `http://localhost:8080/multiple/3/5' then the response
body in my browser should be `15`.

Consider the following URL/Response body pairs as tests:

```
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/ => <html>Here's how to use this page...</html>
```

To submit your homework:

* Fork this repository (Session03).
* Edit this file to meet the homework requirements.
* Your script should be runnable using `$ python calculator.py`
* When the script is running, I should be able to view your
application in my browser.
* I should also be able to see a home page (http://localhost:8080/)
that explains how to perform calculations.
* Commit and push your changes to your fork.
* Submit a link to your Session03 fork repository!


"""

def home():

return Template.home()

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

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)

# TODO: Add functions for handling more arithmetic operations.

def resolve_path(path):
"""
Should return two values: a callable and an iterable of
arguments.
"""

# TODO: Provide correct values for func and args. The
# 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
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):
# TODO: Your application code from the book database
# work here as well! Remember that your application must
# invoke start_response(status, headers) and also return
# the body of the response in BYTE encoding.
#
# 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_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__':
# 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()
28 changes: 28 additions & 0 deletions templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

class Template():

def home():

return '''
<head>
<title>Internet Programming in Python: wsgi-calculator Assignment</title>
</head>
<body>
<h1>Internet Programming in Python: wsgi-calculator Assignment</h1>
<h2>Please follow the format below to operate the calculator:</h2>
<p>For multiplacation: http://localhost:8080/multiply/3/5</p>
<p>For addition: http://localhost:8080/add/23/42</p>
<p>For subtraction: http://localhost:8080/subtract/23/42</p>
<p>For division: http://localhost:8080/divide/22/11</p> 
</body>
'''

def answer(operation, ans):

page = '''
<h1>The answer for the {} operation is: {}.</h1>
'''
return page.format(operation, ans)



2 changes: 1 addition & 1 deletion tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class WebTestCase(unittest.TestCase):
def setUp(self):
self.server_process = subprocess.Popen(
[
"python",
"python3",
"calculator.py"
],
stdout=subprocess.PIPE,
Expand Down