From ac78bc9490a577da4dd83227efcac86d0fbdd773 Mon Sep 17 00:00:00 2001 From: seaneightysix Date: Sat, 20 Jul 2019 12:06:47 -0500 Subject: [PATCH] completed --- __pycache__/templates.cpython-36.pyc | Bin 0 -> 1240 bytes calculator.py | 155 +++++++++++++++------------ templates.py | 28 +++++ tests.py | 2 +- 4 files changed, 116 insertions(+), 69 deletions(-) create mode 100644 __pycache__/templates.cpython-36.pyc create mode 100644 templates.py diff --git a/__pycache__/templates.cpython-36.pyc b/__pycache__/templates.cpython-36.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4575ec3aa3f92ada0fd9f63b9fb6d85f5ed741bf GIT binary patch literal 1240 zcmbtU&2G~`5MDcO6ecmIIgo7~kgCXv%8x)?qDYjBC9t;MB{sFaW_LrBwmH#v z;L4TP;4ysVEjTf|PMsgMy|B`b$1^+M?2Ny0e{XO1N9ce2)I#VFT3hgrj$x}uAl@Q| zm~#dDyBi|rzDM0w4EAQZpdG_jPe5=KIt+y_bC`RD!WL^W51t;|fw*?nIpKMkQO!3H z90+`65Ihjffs^iNDghT`ybIf|AmNk^n^$8CbgDBxd{<~L3$F24iixCoo)#0F7I-|@ zi6{nmrY7mrm}c=5G7E`cD3wl%oEJJEH9~_Lkj*T?sbKT1q{-obWrXl1oh>5qhvSS> z#qnp6WnzYPVpN$^jZe8X2rNo2p>5W;DrEro^|#>4;TxzipJqCRPRCTIrU!}E<$#b( zKyV_I9vmGU9gyXzIq8$<0V!`pqKu_A#w{RlfcSm#%)bpmO;5F?@m&|WKC%L`-`tAL zZq?Xw(FqWR7HY<&;fv+Q#bQYnXbw)*0ADP6K$11ib)BkRv#Z+*@7275 z!(j`MLa(F~zSaSAp{iZycnrFoP~>^e`NO7)+B@p*RGla)XwIXk+Kr-IuxV!W`%(0D tO0(J{O($gAh|NArlS-ODfw9{>9k;V@Eu*eupEre6ouJM%v~duN{sE5$Ic@*| literal 0 HcmV?d00001 diff --git a/calculator.py b/calculator.py index a46affd..ab1007d 100644 --- a/calculator.py +++ b/calculator.py @@ -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/ => Here's how to use this page... -``` - -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 = '

Not Found

' + except Exception: + status = '500 Internal Server Error' + body = '

Internal Server Error

' + 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() diff --git a/templates.py b/templates.py new file mode 100644 index 0000000..2274791 --- /dev/null +++ b/templates.py @@ -0,0 +1,28 @@ + +class Template(): + + def home(): + + return ''' + + Internet Programming in Python: wsgi-calculator Assignment + + +

Internet Programming in Python: wsgi-calculator Assignment

+

Please follow the format below to operate the calculator:

+

For multiplacation: http://localhost:8080/multiply/3/5

+

For addition: http://localhost:8080/add/23/42

+

For subtraction: http://localhost:8080/subtract/23/42

+

For division: http://localhost:8080/divide/22/11

  + + ''' + + def answer(operation, ans): + + page = ''' +

The answer for the {} operation is: {}.

+ ''' + return page.format(operation, ans) + + + diff --git a/tests.py b/tests.py index c2a8dcb..c4192d7 100644 --- a/tests.py +++ b/tests.py @@ -10,7 +10,7 @@ class WebTestCase(unittest.TestCase): def setUp(self): self.server_process = subprocess.Popen( [ - "python", + "python3", "calculator.py" ], stdout=subprocess.PIPE,