def _search_library(keyword): url = 'http://search.snlib.net/search/resultSearchList' try: params = urlencode({'searchKeyword':keyword, 'searchKey':2, 'curPage':1, 'searchLibrary':'MB'}) html = urlopen(url, params) print html except HTTPError as e: # print e return None try: bsObj = BeautifulSoup(html.read()) booklist = bsObj.find('ul', {'class':'booklistText'}) tags = booklist.find_all('a') search_books = [] for tag in tags: book = Book() s = tag['onclick'] p = re.compile('javascript:viewSearchDetail\((\d+)\)') m = p.search(s) book.name = tag.get_text() book.book_id = int(m.groups(0)[0]) search_books.append(book) except AttributeError as e: return None return search_books
def _search_library(keyword): url = 'http://search.snlib.net/search/resultSearchList' try: params = urlencode({ 'searchKeyword': keyword, 'searchKey': 2, 'curPage': 1, 'searchLibrary': 'MB' }) html = urlopen(url, params) print html except HTTPError as e: # print e return None try: bsObj = BeautifulSoup(html.read()) booklist = bsObj.find('ul', {'class': 'booklistText'}) tags = booklist.find_all('a') search_books = [] for tag in tags: book = Book() s = tag['onclick'] p = re.compile('javascript:viewSearchDetail\((\d+)\)') m = p.search(s) book.name = tag.get_text() book.book_id = int(m.groups(0)[0]) search_books.append(book) except AttributeError as e: return None return search_books
def create(): author_1 = Author.create(name = 'Robert Cecil Martin') author_2 = Author.create(name = 'Gary Gygax') author_3 = Author.create(name = 'Nicholas Checan') book_1 = { 'title': 'Clean Architecture', 'author_id': author_1, } book_2 = { 'title': 'Clean Code', 'author_id': author_1, } book_3 = { 'title': 'Advanced Dungeons and Dragons', 'author_id': author_2, } # Set an array of books and insert it into the database books = [book_1, book_2, book_3] Book.insert_many(books).execute() print("Create: OK")
def actionCalled(self): """ Prikazuje dijalog za unos imena nove knjige, kreira novu instancu knjige sa unetim imenom """ parent = QApplication.instance().model newName, ok = QInputDialog.getText(None, "New Book name", "Enter desired new name") if ok: if parent.isValidName(newName): newBook = Book(newName) book = QApplication.instance().mainWindow.newTab(newBook) parent.addChild(book) else: while not parent.isValidName(newName): dialog = QMessageBox() dialog.setWindowTitle("Error") dialog.setText("That name is not valid") dialog.setWindowIcon(QIcon("src/notification.png")) dialog.setModal(True) dialog.exec_() newName, cancel = QInputDialog.getText( None, "New Book name", "Enter desired new name") if not cancel: break else: if parent.isValidName(newName): newBook = Book(newName) book = QApplication.instance().mainWindow.newTab( newBook) parent.addChild(book) break
def info(book_name, client_name): book_id = len(books) book = Book(book_id, book_name) book.printMe() client_id = len(clients) client = Client(client_id, client_name, book) client.printMe() return [client, book]
def read(): book = Book.get(Book.title == 'Advanced Dungeons and Dragons') print(book.title) books = Book.select().join(Author).where( Author.name == 'Robert Cecil Martin') # Display the quantity of registers found in the search process print(books.count()) for book in books: print(book.title)
def newTab(self, root): """ Inicijalizuje novi tab Return: Objekat book """ if len(root.getChildren()) == 0: newName, ok = QInputDialog.getText( None, "New Chapter name", "Enter desired first chapter name") if not ok or newName == "": while not ok or newName == "": newName, ok = QInputDialog.getText( None, "New Chapter name", "Enter desired first chapter name") root.addChild(Chapter(newName)) book = Book(root.getName()) book.setPath(root.getPath()) book.setParent(QApplication.instance().model) rootModel = HierarchyTreeModel(book) rootView = HierarchyTreeView(rootModel) for chapter in root.getChildren(): tmpChapter = Chapter(chapter.getName()) book.addChild(tmpChapter) for page in chapter.getChildren(): tmpPage = Page(page.getName()) tmpChapter.addChild(tmpPage) for element in page.getChildren(): element.setParent(tmpPage) tmpPage.addChild(element) self.tabs.addTab(rootView, root.getName()) self.LeftButton.clicked.connect(rootView.leftButtonPressed) self.RightButton.clicked.connect(rootView.rightButtonPressed) rootView.SelectRoot() return book
def readPage(self, response): soup = BeautifulSoup(response.body, 'lxml') menu = soup.findAll('div', {'class': 'manga-focus'}) for item in menu: a = item.findAll('a')[0] # print a.text.encode('utf-8', 'ignore').strip(), a.get('href').strip() book = Book() book.book_name = a.text.encode('utf-8', 'ignore').strip() link = a.get('href').strip() yield scrapy.Request(link, callback=self.readDetail, meta={'book': book}) """debug""" break
def readEachCategory(self, response): soup = BeautifulSoup(response.body,'lxml') listBook = soup.findAll('div', {'class' : 'manga_list'}) for bookEle in listBook: listA = bookEle.findAll('a') book = Book() book.book_name = listA[0].get('title').encode('utf-8') book.book_site = self.site book.book_id = self.bookDBManager.addNewBook(book) yield scrapy.Request(listA[0].get('href'), callback=self.readDetailBook, meta={'book': book} ) break
def get(self): data = self.request.get('data') key_word = self.request.get('key_word') logging.info(key_word) if data == 'json' and key_word == '': self.response.headers['Content-Type'] = 'text/json' book = Book.query() items = json.dumps([item.to_dict() for item in book.fetch()], default=str) logging.info(items) self.response.out.write(items) return elif data == 'json' and key_word != '': self.response.headers['Content-Type'] = 'text/json' key_word = self.request.get('key_word') data = Search.search_items(key_word) logging.info(data) self.response.out.write(json.dumps(data, default=str)) return jinja_environment = self.jinja_environment template = jinja_environment.get_template('/index.html') self.response.out.write(template.render())
def get(self): if self.request.get('delete_book_id') != '': self.response.out.headers['Content-Type'] = 'text/json' book_id = self.request.get('delete_book_id') json_data = json.dumps([book.to_dict() for book in Book.query(Book.Id == book_id).fetch()], default=str) logging.info(json_data) self.response.out.write(json_data) return
def update(): new_author = Author.get(Author.name == 'Nicholas Checan') book = Book.get(Book.title == "Clean Architecture") # Change the book author book.author = new_author book.save() print("Update: OK")
def get_user_log(self, user_id): command = 'SELECT * FROM `frc_library`.`books` WHERE `borrower_id` = %s' db = sql.connect(self.host, self.user, self.password, self.name) cursor = db.cursor() cursor.execute(command, user_id) results = cursor.fetchall() books = [] for result in results: books.append( Book(result[0], result[1], bool(result[2]), result[3], result[4])) return books
def query_book(self, book_id): command = 'SELECT * FROM `frc_library`.`books` WHERE `book_id` = %s;' db = sql.connect(self.host, self.user, self.password, self.name) cursor = db.cursor() cursor.execute(command, book_id) result = cursor.fetchone() cursor.close() db.close() if result: return Book(result[0], result[1], bool(result[2]), result[3], result[4]) else: return None
def get_books(self): book_list = [] url = util.Dbt.Dbt.get_api_url("/library/book", {"dam_id": self.damn_id}) books = util.Dbt.Dbt.get_request(url) for book in books: b = Book(self, book['book_name'], book['book_id'], book['book_order']) list_chapters = book['chapters'].split(',') for c in list_chapters: b.chapters.append(Chapter(b, c)) book_list.append(b) return book_list
def post(self): book_id = self.request.get('update_book_id') book_name = self.request.get('update_book_name') book_type = self.request.get('update_book_type') book_date = self.request.get('update_book_date') book_date = datetime.strptime(book_date, "%d/%m/%Y").strftime("%Y-%m-%d") book = Book.query(Book.Id == book_id).get() if book: book.Id = book_id book.Name = book_name book.Type = book_type book.Date = datetime.strptime(book_date, '%Y-%m-%d') data = Search.update_book_to_index(book) logging.info(data) book.put()
def post(self): logging.info(self.request.get('book_name')) logging.info(self.request.get('book_type')) logging.info(self.request.get('book_date')) book_id = str(random.randint(1, 100)) id_entity = Book.query(Book.Id == book_id).fetch() if book_id != '' and id_entity: book_id = str(random.randint(101, 500)) book_name = self.request.get('book_name') book_type = self.request.get('book_type') book_date = self.request.get('book_date') book_date = datetime.strptime(book_date, "%d/%m/%Y").strftime("%Y-%m-%d") book = Book(Id=book_id, Name=book_name, Type=book_type, Date=datetime.strptime(book_date, "%Y-%m-%d")) data = Search.create_book(book) Search.add_book_to_index(data) book.put() else: book_name = self.request.get('book_name') book_type = self.request.get('book_type') book_date = self.request.get('book_date') book_date = datetime.strptime(book_date, "%d/%m/%Y").strftime("%Y-%m-%d") book = Book(Id=book_id, Name=book_name, Type=book_type, Date=datetime.strptime(book_date, "%Y-%m-%d")) data = Search.create_book(book) Search.add_book_to_index(data) book.put()
def find_book(vers, book_name): version = Dbt.find_version(vers) for t in version.testaments: url = Dbt.get_api_url("/library/book", {"dam_id": t.damn_id}) books = Dbt.get_request(url) for book in books: if Dbt.book_equals(book['book_name'], book_name): b = Book(t, book['book_name'], book['book_id'], book['book_order']) list_chapters = book['chapters'].split(',') for c in list_chapters: b.chapters.append(Chapter(b, c)) return b return None
def get_book_info(self): # 定义一个book类的集合 self.bookSet = set() # 获取到所有书籍的内容 self.BookInfoList = self.soup.find_all('li', class_='subject-item') # 遍历每本书籍,获取每本书籍的信息 for every in self.BookInfoList: # 创建一个book书籍对象 book = Book("", "", "", 0.0, "", "", 0.00) self.bookInfo = every.find('div', class_='info') # 书名 if "\'" in self.bookInfo.find('a')['title']: self.bookInfo.find('a')['title'] = self.bookInfo.find( 'a')['title'].replace("'", "\\\'") book.set_book_name(self.bookInfo.find('a')['title']) # 评分 # print(self.bookInfo.find('span', class_ = 'rating_nums').get_text()) if self.bookInfo.find('span', class_='rating_nums'): if self.bookInfo.find('span', class_='rating_nums').get_text(): book.set_score( self.bookInfo.find('span', class_='rating_nums').get_text()) else: book.set_score(0.0) else: book.set_score(0.0) # 其他信息 self.otherInfo = self.bookInfo.find('div', class_='pub').get_text() self.otherInfoStrip = self.otherInfo.strip() # todo 修改参数 self.otherInfoList = self.otherInfoStrip.split("/") # 将单引号进行转换 for i in range(0, len(self.otherInfoList)): if "\'" in self.otherInfoList[i]: self.otherInfoList[i] = self.otherInfoList[i].replace( "'", "\\\'") book.set_author(self.otherInfoList[0]) if len(self.otherInfoList) == 4: book.set_publish(self.otherInfoList[1]) book.set_publish_date(self.otherInfoList[2]) # if len(self.otherInfoList[-1]) >7: # book.set_price(0.0) # else: book.set_price(self.otherInfoList[3]) elif len(self.otherInfoList) == 5: book.set_translater(self.otherInfoList[1]) book.set_publish(self.otherInfoList[2]) book.set_publish_date(self.otherInfoList[3]) # if len(self.otherInfoList[-1]) > 6: # book.set_price(0.0) # else: book.set_price(self.otherInfoList[4]) else: book.set_price(self.otherInfoList[-1]) # todo 需要适配其他的情况 # 先把一个book对象格式化 book = self.change_type(book) self.bookSet.add(book) return self.bookSet
def post(self): book_id = self.request.get('delete_book_id') book = Book.query(Book.Id == book_id).get() if book: Search.delete_index(book_id) book.key.delete()
import json from model.Book import Book app = Flask(__name__) booksJson = [{'id': 1, 'titre': 'un titre'}, {'id': 2, 'titre': 'un autre titre random'}] bookListObject = [] with open('json/books.json', 'r') as json_book: book_data = json.loads(json_book.read()) for book in book_data: # print("book : ", book) # print("\n") # print(json.dumps(book)) try: bookListObject.append( Book(**book) ) except: pass print('book list ', bookListObject.__str__()) @app.route("/") @app.route("/index/") def index(): return render_template('index.html', title="Books", titleh1="hello my app") @app.route("/ma_route/") def name():
import peewee from model.Author import Author from model.Book import Book # Samples - Test purpose from sample.create import create from sample.read import read from sample.update import update from sample.delete import delete if __name__ == '__main__': try: Author.create_table() print("'Author' table successfully created!") except peewee.OperationalError: print("'Author' already exist!") try: Book.create_table() print("'Book' table successfully created!") except peewee.OperationalError: print("'Book' already exist!") create() # Example: Books and authors data creation read() # Example: Read books and authors update() # Example: Update a book register delete() # Example: Delete a book register
def parse(book_info): (name, author, price) = book_info.split(';') book = Book(name, author, price) return (book)