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
', '']
+ item_template = '- {title}
'
+ for book in all_books:
+ body.append(item_template.format(**book))
+ body.append('
')
+ 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