def application(environ, start_response): global messages status = '200 OK' response_headers = [('Content_type', 'text/HTML')] start_response(status, response_headers) # send different page depending on URL path path = environ['PATH_INFO'] db = BookDB() if path == '/index.html': book_list = db.titles() strings = [] for book in book_list: book_id = book['id'] book_title = book['title'] strings.append(book_id) strings.append(book_title) page = index_template % ( strings[0], strings[1], strings[2], strings[3], strings[4], strings[5], strings[6], strings[7], strings[8], strings[9]) elif path == '/detail.html/': book_id = \ urlparse.parse_qs(environ['QUERY_STRING'])['book_id'][0] book_info = db.title_info(book_id) page = detail_template % (book_info['title'], book_info['title'], book_info['isbn'], \ book_info['publisher'], book_info['author']) else: page = notfound_template % path return [page] # list of strings - must return iterable, not just a string
def application(environ, start_response): global messages status = '200 OK' response_headers = [('Content_type', 'text/HTML')] start_response(status, response_headers) # send different page depending on URL path path = environ['PATH_INFO'] db = BookDB() if path == '/index.html': book_list = db.titles() strings = [] for book in book_list: book_id = book['id'] book_title = book['title'] strings.append(book_id) strings.append(book_title) page = index_template % (strings[0],strings[1],strings[2], strings[3],strings[4],strings[5], strings[6],strings[7],strings[8], strings[9]) elif path == '/detail.html/': book_id = \ urlparse.parse_qs(environ['QUERY_STRING'])['book_id'][0] book_info = db.title_info(book_id) page = detail_template % (book_info['title'], book_info['title'], book_info['isbn'], \ book_info['publisher'], book_info['author']) else: page = notfound_template % path return [ page ] # list of strings - must return iterable, not just a string
def __init__(self): self.reader = CodeReader() self.db = BookDB(RegisterBooks.LIBRARIAN_DB_NAME) self.db.create_table() outdir = pathlib.Path(RegisterBooks.BOOKS_QRCODE_DIR) if not outdir.exists(): outdir.mkdir()
def my_admin_load_BooksDB(): my_books=BookDB() book_count=-1 for my_book in my_books.titles(): save_book( my_book['id'], my_books.title_info(my_book['id'])['isbn'].replace('-',''),my_books.title_info(my_book['id'])['title'], my_books.title_info(my_book['id'])['author'], my_books.title_info(my_book['id'])['publisher'] )
def index(environ, start_response): """ This function will be mounted on "/" and display a link to the hello world page.""" bob = BookDB() books = bob.titles() str = "" for i in books: str += '<p>%s <a href ="/info/%s/">info</a><p/>' %(i['title'], i['id']) start_response('200 OK', [('Content-Type', 'text/html')]) return [str]
def detail(self, id): books = BookDB() bookdet = books.title_info(id) template = Template(''' <h1>Book Details</h1><hr> <h2>Title: $bookdet['title']</h2><br> <b>ISBN:</b> $bookdet['isbn']<br> <b>Publisher:</b> $bookdet['publisher']<br> <b>Author:</b> $bookdet['author']<br><br> <a href="./">Return to List</a> ''', [locals(), globals()]) return template.respond()
def info(environ, start_response): """ This function displays a page for each of the books in the database.""" parameters = environ.get('PATH_INFO', "").split('/') subject = str(parameters[2]) if "" == subject: start_response('400 No Content', [('Content-Type', 'text/html')]) else: bob = BookDB() steve = bob.title_info(subject) stri = "" start_response('200 OK', [('Content-Type', 'text/html')]) for i in steve.keys(): stri += '<p>%s : %s<p/>' %(i, steve[i]) stri += '<p><a href ="/">BACK</a><p/>' return [stri] print '---->' + str(parameters[2])
def my_admin_load_BooksDB(): my_books = BookDB() book_count = -1 for my_book in my_books.titles(): save_book(my_book['id'], my_books.title_info(my_book['id'])['isbn'].replace('-', ''), my_books.title_info(my_book['id'])['title'], my_books.title_info(my_book['id'])['author'], my_books.title_info(my_book['id'])['publisher'])
from bookdb import BookDB from pprint import pprint bob = BookDB() books = bob.titles() str = "" for i in books: str += i['title'] + '\n' print str hmm = books[1]['id'] steve = bob.title_info(hmm) pprint(steve)
def __init__(self): self.bookdb = BookDB() self.safaribook = None
def index(self): books = BookDB() env = Environment(loader=FileSystemLoader('templates')) tmpl = env.get_template('booklist.html') return tmpl.render(books=books.titles())
class Book: def __init__(self): self.bookdb = BookDB() self.safaribook = None def init_safari(self, bookid): self.args = Args() self.args.bookid = bookid print("login account: " + self.args.cred) print("book id :" + self.args.bookid) cred = WebSafariBooks.parse_cred(self.args.cred) if not cred: print("invalid credential: %s" % self.args.cred) self.args.cred = cred self.safaribook = WebSafariBooks(self.args) def download(self, bookid): book_path = "" # if (self.safaribook == None): self.init_safari(bookid) book_path = self.safaribook.download(self.args) return book_path def validate_id(self, bookid): match = re.search(r'^[\d]+$', bookid) return match def validate(self, bookid): if (bookid == None or not bookid.strip()): return {'code': 3, 'message': 'Book ID is empty '} if self.validate_id(bookid) == None: return {'code': 3, 'message': 'Invalid Book ID ' + bookid} # check book exist in db abook = self.bookdb.checkExist(bookid) if (abook != None): print("Book already inserted in DB") return {'code': 2, 'message': 'Book already added'} else: print("start get book info from API: " + bookid) if (self.safaribook == None): self.init_safari(bookid) book_info = self.safaribook.web_get_book_info() pprint(book_info) if (book_info == 0): return {'code': 1, 'message': 'API: unable to retrieve book info'} elif not isinstance(book_info, dict) or len(book_info.keys()) == 1: if "detail" in book_info: return {'code': 1, 'message': book_info['detail']} else: return {'code': 1, 'message': 'Query book info failed'} else: print("query book info ok") self.safaribook.init_download(book_info) num_author = len(book_info['authors']) count = 0 book_info['authorsName'] = '' for author in book_info['authors']: count += 1 if (count < num_author): book_info['authorsName'] += author['name'] + ", " else: book_info['authorsName'] += author['name'] book_info['downloadStatus'] = Status.QUEUED.value book_info['downloadCount'] = 0 book_info['addedDate'] = datetime.now() book_info['downloadStart'] = "" book_info['downloadEnd'] = "" book_info['downloadLog'] = "" book_info['downloadPath'] = "" book_info['downloadTmpPath'] = os.path.join( self.safaribook.BOOK_PATH, "OEBPS") self.bookdb.insert(book_info) book_info['code'] = 0 return book_info def list(self): simple_list_book = [] listbook = self.bookdb.list() return listbook # Redownload multi books def redownload(self, bookids): redownload_bookids = {} for bookid in bookids: abook = self.bookdb.checkExist(bookid) if (abook): #book in DB # update db status print('Update book {} to queue'.format(bookid)) self.bookdb.flagQueued(bookid) #delete local file print('Delete temp path {} for book {}'.format( abook['downloadTmpPath'], bookid)) shutil.rmtree(abook['downloadTmpPath'], True) if os.path.exists(abook['downloadPath']): print('Delete book path {} for book {}'.format( abook['downloadPath'], bookid)) os.remove(abook['downloadPath']) redownload_bookids[bookid] = Status.QUEUED.value else: print('book not exist : ' + bookid) redownload_bookids[bookid] = Status.NOTEXIST.value return redownload_bookids # Delete many books def delete(self, bookids): deleted_bookids = {} for bookid in bookids: abook = self.bookdb.checkExist(bookid) if (abook): # book in DB #delete local file shutil.rmtree(abook['downloadTmpPath'], True) if os.path.exists(abook['downloadPath']): os.remove(abook['downloadPath']) # delete from db self.bookdb.delete(bookid) deleted_bookids[bookid] = Status.NOTEXIST.value else: print('book not exist : ' + bookid) deleted_bookids[bookid] = Status.NOTEXIST.value return deleted_bookids def log(self, bookid): PATH = os.path.dirname(os.path.realpath(__file__)) log_file = "log/info_%s.log" % escape(bookid) log_full_path = os.path.join(PATH, log_file) print(log_full_path) if (os.path.exists(log_full_path)): with open(log_full_path, 'r') as f: return "<pre>" + f.read() + "</pre>" else: return "Download is not start for book: " + bookid
def makeOne(self): from bookdb import BookDB return BookDB()
__author__ = 'matt' """ Testing methods in the books class, from books_test.py. """ if __name__ == '__main__': from bookdb import BookDB books = BookDB() print books.titles() print books.title_info('id1')
def index(): db = BookDB() book_dict = db.titles() import pdb; pdb.set_trace() return index_template % book_dict
Send HTML page that echoes message from HTTP request To get started, point browser at echo_flask.html """ from flask import Flask, render_template, request from bookdb import BookDB app = Flask(__name__) app.debug = True # development only - remove on production machines # View functions generate HTTP responses including HTML pages and headers db = BookDB() ''' This function gets a dict of the ids and titles from the database and passes it to the template. ''' @app.route('/index.html/') def index(): return render_template('index.html', titles=db.titles()) ''' This function takes a book id and gets the title info from the database as a dict. This dict is passed to the template. ''' @app.route('/book_details/<book_id>') def detail(book_id=None): return render_template('detail.html', details=db.title_info(book_id))
def database(): from bookdb import BookDB return BookDB()
class RegisterBooks: LIBRARIAN_DB_NAME = "librarian.db" GBOOKS_API_URL = 'https://www.googleapis.com/books/v1/volumes?q=isbn:' BOOKS_QRCODE_DIR = './books_qrcode' def __init__(self): self.reader = CodeReader() self.db = BookDB(RegisterBooks.LIBRARIAN_DB_NAME) self.db.create_table() outdir = pathlib.Path(RegisterBooks.BOOKS_QRCODE_DIR) if not outdir.exists(): outdir.mkdir() # def __del__(self): # pass def search_book_with_isbn(self, isbn): req_url = RegisterBooks.GBOOKS_API_URL + str(isbn) response = requests.get(req_url) return response def get_booktitle_from_gbsapi(self, json_data): try: title = json_data['items'][0]['volumeInfo']['title'] except : title = None return title def print_start_msg(self): print("") print("Register New Books for book database.") print("step1 : Scan new books over and over") print("step2 : push ESC key to save and quit") print("------") print(">>> NOTE1 ") print(">>> - if failed to get isbncode with scaning book,") print(">>> - input isbncode with keyboard, please.") print(">>> NOTE2 ") print(">>> - if failed to get book info from Web,") print(">>> - input book title with keyboard, please.") print("") print("") # main process loop until input ESC def start(self): # =========================================================== # scanning books and getting books' info phase # =========================================================== registerd_count = 0 self.print_start_msg() while True: # ---------------------------------------------------- # Get ISBN code # ---------------------------------------------------- ret, code = self.reader.read() # カメラからISBNコードをとれない場合は手入力 if ret == -1: print("input isbn code with keyboard ...") print("NOTE : isbn consists of 13 numbers") code = input() # ESCを押したら保存せずにアプリケーションを終了 elif ret == -2: print("save and quit ... ") break # ---------------------------------------------------- # Get Book's info with ISBN code # ---------------------------------------------------- response = self.search_book_with_isbn(code) json_data = response.json() book_title = self.get_booktitle_from_gbsapi(json_data) # APIから本のタイトルが取得できない場合は手入力 if book_title is None: print('sorry cant find that book ... isbn = ' + str(code)) print('input book title , please.') book_title = input() # 登録する情報を表示する print("isbn: " + str(code) + ", title: " + str(book_title)) # ---------------------------------------------------- # Register for DB # ---------------------------------------------------- self.db.insert_book_record( isbn=str(code), title=book_title, status=0) registerd_count += 1 # =========================================================== # generate book's unique QR code image # =========================================================== registered_data = self.db.select_table_lastNdata_as_df(datanum=registerd_count) if registered_data is None: return for row in registered_data.itertuples(): # QR code string qrcode_str = str(row[1]) + "_" + str(row[2]) # QR code image file name title_str = str(row[3]).strip()[:10] qrcode_filename = str(row[1]) + "_" + title_str + ".png" # output QR code png file qrcode_img = qrcode.make(qrcode_str) qrcode_img.save(RegisterBooks.BOOKS_QRCODE_DIR + '/' + qrcode_filename) # debug code print(row)
def my_admin_load_BooksDB(request): my_books=BookDB()
def detail(book_id=None): db = BookDB() return detail_template % (db.title_info(book_id))
import re from bookdb import BookDB DB = BookDB() def book(book_id): page = """ <h1>%(title)s</h1> <table> <tr><th>Author</th><td>%(author)s</td></tr> <tr><th>Publisher</th><td>%(publisher)s</td></tr> <tr><th>ISBN</th><td>%(isbn)s</td></tr> </table> <a href="/">Back to the list</a> """ book = DB.title_info(book_id) if book is None: raise NameError return page % book def books(): all_books = DB.titles() body = ['<h1>My Bookshelf</h1>', '<ul>'] item_template = '<li><a href="/book/%(id)s">%(title)s</a></li>' for book in all_books: body.append(item_template % book) body.append('</ul>') return '\n'.join(body)
def __init__(self): self.bookdb = BookDB() self.book = Book()
""" My book navigator """ from flask import Flask, render_template, request from bookdb import BookDB app = Flask(__name__) app.debug = True # development only - remove on production machines # View functions generate HTTP responses including HTML pages and headers all_books = BookDB() #Show the welcome page @app.route('/welcome.html') def welcome(): return render_template('welcome.html') #Show the index page @app.route('/index.html') def index(): return render_template('index.html', books=all_books) #Show details page @app.route('/book.html') def book_info(): #render the template for the selected book based on the id tag
class Worker: def __init__(self): self.bookdb = BookDB() self.book = Book() def run(self): print("Start worker at: {}".format(datetime.now())) list_queued = self.bookdb.listQueued() list_retry = self.bookdb.listRetry() print("Queued book : " + str(list_queued.count())) print("Retry book : " + str(list_retry.count())) for book in list_queued: bookid = book['identifier'] print("Start to download " + bookid) self.bookdb.flagDownloading(bookid) try: path = self.book.download(bookid) self.bookdb.flagSuccess(bookid, path) except Exception as err: print("Error download book " + bookid, err) self.bookdb.flagFailed(bookid, str(err)) for book in list_retry: bookid = book['identifier'] print("Start to retry " + bookid) self.bookdb.flagRetrying(bookid) try: path = self.book.download(bookid) self.bookdb.flagSuccess(bookid, path) except Exception as err: print("Error download book " + bookid, err) self.bookdb.flagFailed(bookid, str(err)) print("Worker done at: {}".format(datetime.now()))
def index(): db = BookDB() book_dict = db.titles() import pdb pdb.set_trace() return index_template % book_dict
def BookDetail(self, id): books = BookDB() env = Environment(loader=FileSystemLoader('templates')) tmpl = env.get_template('bookdetail.html') return tmpl.render(detail=books.title_info(id))