From d61a09e6d9a6633f8e854e7c70b47a428e1b2371 Mon Sep 17 00:00:00 2001 From: Zhen Yang Date: Sat, 13 Jun 2020 17:00:33 -0700 Subject: [PATCH] finished activity for lesson04 --- bookapp.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/bookapp.py b/bookapp.py index d2284c6..cb48e5a 100644 --- a/bookapp.py +++ b/bookapp.py @@ -1,24 +1,74 @@ import re - +import traceback from bookdb import BookDB DB = BookDB() def book(book_id): - return "

a book with id %s

" % book_id + body = """

{title}

+ + + + +
Author:{author}
Publisher:{publisher}
ISBN:{isbn}
+ Back to the list + """ + the_book = DB.title_info(book_id) + if the_book is None: + raise NameError + return body.format(**the_book) def books(): - return "

a list of books

" + all_books = DB.titles() + body = ['

My Bookself

', '') + return '\n'.join(body) +def book_router(path): + functions = { + '': books, + 'book': book + } + # strip the last '/', then split the path into words by + # "/" + # so localhost:8080/ should be [] + # localhost:8080/book/id1/ should be [book] [id1] + # localhost:8080/book/id2/ should be [book] [id2] + 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): - status = "200 OK" headers = [('Content-type', 'text/html')] - start_response(status, headers) - return ["

No Progress Yet

".encode('utf8')] - + try: + path = environ.get("PATH_INFO", None) + if path is None: + raise NameError + func, args = book_router(path) + body = func(*args) + status = "200 OK" + except NameError: + status = '404 Not Found' + body = '

404 Not Found

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

Internal Server Error

' + print(traceback.format_exc()) + finally: + headers.append(('Content-len', str(len(body)))) + start_response(status, headers) + return [body.encode('utf8')] if __name__ == '__main__': from wsgiref.simple_server import make_server