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

michael_mcdonald submitting lesson4 assignment wsgi-calculator #31

Open
wants to merge 2 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
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/inspectionProfiles/profiles_settings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions .idea/wsgi-calculator.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

203 changes: 132 additions & 71 deletions calculator.py
Original file line number Diff line number Diff line change
@@ -1,84 +1,145 @@
"""
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.

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!


"""
"""a simple math application"""
import traceback


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
my_sum = 0
for my_arg in args:
my_sum += int(my_arg)
page = f"""
<h1>Addition</h1>
<div>{my_sum}</div>
<div><a href="/">Back to index</a></div>
"""
return page


def subtract(*args):
"""subtract input numbers"""

my_sum = int(args[0])
sliced_tuple = args[1:]
print(sliced_tuple)
for my_arg in sliced_tuple:
print(my_sum)
my_sum = my_sum - int(my_arg)
page = f"""
<h1>Subtraction</h1>
<div>{my_sum}</div>
<div><a href="/">Back to index</a></div>
"""
return page


def multiply(*args):
"""multiply input numbers"""

my_sum = int(args[0])
sliced_tuple = args[1:]
print(sliced_tuple)
for my_arg in sliced_tuple:
print(my_sum)
my_sum = my_sum * int(my_arg)
page = f"""
<h1>Multiplication</h1>
<div>{my_sum}</div>
<div><a href="/">Back to index</a></div>
"""
return page


def divide(*args):
"""divide input numbers"""

try:
my_sum = int(args[0])
sliced_tuple = args[1:]
print(sliced_tuple)
for my_arg in sliced_tuple:
print(my_sum)
my_sum = my_sum / int(my_arg)
page = f"""
<h1>Division</h1>
<div>{my_sum}</div>
<div><a href="/">Back to index</a></div>
"""
except ZeroDivisionError:
page = """
<h1>500 Internal Server Error</h1>
<h2>Divide by zero error</h2>
<div><a href="/">Back to index</a></div>
"""
print(traceback.format_exc())
return page
return page

# 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']

""" returns two values: a callable and an iterable of arguments. """

funcs = {'': index, '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 index():
"""create an entry page for the application"""

page = """
<h1>Calculator</h1>
<div>Directions. This app will calculate 2 or more numbers provided in the url string. To use:
<ol>
<li>Type in http://localhost:8080/</li>
<li>Type in the arithmetic operation (add, subract, multiply, divide) followed by /</li>
<li>Type in numbers. Between each number include a /</li>
<li>For example, http://localhost:8080/add/5/10/</li>
</ol></div>
<h2>Tests:</h2><ul>
<li><a href="http://localhost:8080/add/5/10/15">Addition</a></li>
<li><a href="http://localhost:8080/subtract/100/50/25">Subraction</a></li>
<li><a href="http://localhost:8080/multiply/5/10/15">Multiplication</a></li>
<li><a href="http://localhost:8080/divide/100/50">Division</a></li>
"""
return page


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
"""invoke start_response(status, headers) and
start the body of the response in BYTE encoding"""

headers = [("Content-type", "text/html")]
body = ''
status = ''
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()
3 changes: 0 additions & 3 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,9 @@ def get_response(self, url):

conn = http.client.HTTPConnection('localhost:8080')
conn.request('GET', url)

response = conn.getresponse()
self.assertEqual(200, response.getcode())

conn.close()

return response

def test_add(self):
Expand Down