def import_to_database(database_url, file): with open(file, "r") as csvDataFile: reader = csv.DictReader(csvDataFile, delimiter=',') book = None bulk_insert = "INSERT INTO book (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)" data = [] for row in reader: #print(row) book = Book(row['isbn'], row['title'], row['author'], row['year']) if book.is_valid(): data.append({ "isbn": book.isbn, "title": book.title, "author": book.author, "year": book.year }) else: print(f"Could not INSERT {book.isbn}") #print(data) db.execute(bulk_insert, data) db.commit()
def setUp(self): super(TestBook, self).setUp() self.maxDiff = None self.app = create_app() self.session = session user_obj = User(username="******", email="*****@*****.**", password=pbkdf2_sha256.hash("pass")) self.session.add(user_obj) self.session.flush() self.user_id = int(user_obj.id) book_type = BookType(book_type="normal", charge="1.5") self.session.add(book_type) self.session.flush() self.book_type_id = int(book_type.id) book_type = BookType(book_type="fiction", charge="3") self.session.add(book_type) self.session.flush() self.book_type_id_1 = int(book_type.id) book_obj = Book(book_name="python", book_type_id=self.book_type_id) self.session.add(book_obj) self.session.flush() self.book_id = int(book_obj.id) book_obj = Book(book_name="data", book_type_id=self.book_type_id_1) self.session.add(book_obj) self.session.flush() self.book_id_2 = int(book_obj.id) user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=self.book_id) self.session.add(user_book_mapping) self.session.flush() user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=self.book_id_2) self.session.add(user_book_mapping) self.session.flush()
def get(self, book_id=None): #if a book id is sent, return the book if book_id: #if book not found will cause an error try: book = ndb.Key(urlsafe=book_id).get() #make sure is book and not customer assert Book.is_book(book) self.write_json(book.to_json()) except: #error on not found self.response.set_status(404) #return list of all books else: #if request parameter not sent, will be empty string #convert to lowercase so we get case insensitive string comparison #http://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison-in-python checked_out_parameter = self.request.get('checkedIn').lower() #just show books that are not checked in if checked_out_parameter == 'false': books = Book.query(Book.checkedIn == False).fetch() #just show books that are checkedIn elif checked_out_parameter == 'true': books = Book.query(Book.checkedIn == True).fetch() #show all books else: books = Book.all() self.write_json(Book.all_to_json(books))
def update_book(): books = None book = None if request.method == 'GET': book = Book.find_by_id(request.args.get('id')) authors = book.get_book_authors() if (authors): book.authors = ','.join([author[1] for author in authors]) if book: return render_template('update_book.html', book=book) if request.method == 'POST': form = request.form book = Book.find_by_id(form['id']) print(form) if book: book.date = form['date'] book.genre = form['genre'] book.isbn = form['isbn'] book.title = form['title'] book.authors = [ author.strip() for author in request.form['authors'].split(',') ] book.update_book() if book: return render_template('books.html', books=[book]) books = Book.get_all_books() if books: return render_template('books.html', books=books) return render_template('index.html')
class TestBook(unittest.TestCase): def setUp(self): self.book = Book('Harry Potter', 'Fantasy', 'Wizard goes to school', 'J.K Rowling') def test_book_has_title(self): self.assertEqual('Harry Potter', self.book.title) def test_book_has_genre(self): self.assertEqual('Fantasy', self.book.genre) def test_book_has_description(self): self.assertEqual('Wizard goes to school', self.book.description) def test_book_has_author(self): self.assertEqual('J.K Rowling', self.book.author) def test_book_rating_starts_0(self): self.assertEqual(0, self.book.rating) def test_book_id_starts_none(self): self.assertEqual(None, self.book.id) def test_can_change_rating(self): self.book.update_rating(5) self.assertEqual(5, self.book.rating)
def add(self): name = self.get_argument('bookname', None) source = self.get_argument('source', None) author = self.get_argument('author', None) price = float(self.get_argument('price', 0)) upload = int(self.get_secure_cookie('sign')) breif = self.get_argument('breif', None) if not name or not source or not author: self.reply_json_error(1, u'请填写书名,来源或者作者') return b = Book.select(Book.q.bookName == name).count() if b: self.reply_json_error(1, u'本书已经存在,请勿重复添加') return try: book = Book(bookName=name, source=source, author=author, uploadUser=upload, price=price, bookDesc=breif) if book: self.reply_json_data(0, u'书籍添加成功') return else: self.reply_json_error(1, u'书籍添加失败!') return except Exception as e: app_log.error(str(e))
def add_book(): if request.method == 'GET': return render_template('add_book.html') elif request.method == 'POST': authors = [ author.strip() for author in request.form['book_authors'].split(',') ] title = request.form['book_title'] genre = request.form['book_genre'] isbn = request.form['book_isbn'] date = request.form['book_date'] if authors is not None and title != '' and genre != '' and isbn != '' \ and date != '': book = Book(None, isbn, genre, title, date) book.add_book(authors) return redirect(url_for('books')) elif title == "": return render_template('add_book.html', error='Title is reuqered!') elif genre == "": return render_template('add_book.html', error='Genre is reuqered!') elif isbn == "": return render_template('add_book.html', error='ISBN is reuqered!') elif date == "": return render_template('add_book.html', error='Date is reuqered!') elif authors is None: return render_template('add_book.html', error='''At least one author is requred!''')
def book_list(): books = [ Book('Python Flask', 59.00, 'Eason', '人民邮电出版社'), Book('Python Selenium', 59.00, 'Tom', '人民邮电出版社'), Book('Python 爬虫', 39.00, 'Eason', '北京大学出版社'), Book('Python 多线程', 49.00, 'Eason', '清华大学出版社'), Book('Python 语言', 29.00, 'Eason', '人民邮电出版社') ] return render_template('book-list.html', books=books)
def test_get_number_of_books_charge_on_basis_of_story_3(self): with self.app.app_context(): self.session.rollback() user_obj = User(username="******", email="*****@*****.**", password=pbkdf2_sha256.hash("pass")) self.session.add(user_obj) self.session.flush() self.user_id = int(user_obj.id) book_type = BookType(book_type="normal", charge="1.5", fixed_days=2, fixed_charges=2) self.session.add(book_type) self.session.flush() book_type_id_1 = int(book_type.id) book_type = BookType(book_type="fiction", charge="3") self.session.add(book_type) self.session.flush() book_type_id_2 = int(book_type.id) book_type = BookType(book_type="novel", charge="1.5", fixed_days=3, fixed_charges=4.5) self.session.add(book_type) self.session.flush() book_type_id_3 = int(book_type.id) book_obj = Book(book_name="python", book_type_id=book_type_id_1) self.session.add(book_obj) self.session.flush() book_id_1 = int(book_obj.id) book_obj = Book(book_name="data", book_type_id=book_type_id_2) self.session.add(book_obj) self.session.flush() book_id_2 = int(book_obj.id) book_obj = Book(book_name="data", book_type_id=book_type_id_3) self.session.add(book_obj) self.session.flush() book_id_3 = int(book_obj.id) user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=book_id_1) self.session.add(user_book_mapping) self.session.flush() user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=book_id_2) self.session.add(user_book_mapping) self.session.flush() user_book_mapping = UserBookMapping(user_id=self.user_id, book_id=book_id_3) self.session.add(user_book_mapping) self.session.flush() response = get_number_of_books_charge(user_id=self.user_id) self.assertEqual(response, dict(book_charges=9.5, number_of_books=3))
def create_confirmed(): book = Book(request.form['name'].strip(), request.form['directory_url'].strip(), request.form['crawler_name'].strip()) book.description = request.form['description'].strip() os.makedirs(os.path.join(constants.BOOK_IMGS_PATH, book.name)) file = request.files['thumbnail'] if file: filename = utils.gen_unique_filename(secure_filename(file.filename)) file.save(os.path.join(constants.BOOK_THUMBNAILS_PATH, filename)) book.thumbnail_filename = filename db.session.add(book) db.session.commit() return redirect(url_for('.index'))
def load_books(self, file_path): try: with open(file_path, 'r', encoding="iso-8859-1") as csv_file: reader = csv.reader(csv_file, delimiter=';', quotechar='"') # Skip header, next(reader, None) for row in reader: book = Book(isbn=row[0], title=row[1], author=row[2], publish_year=row[3], publisher=row[4]) self._books[book.get_isbn()] = book except Exception as e: self._books = {} print("Could not load books.", e)
def find_book(self) -> Book: books = Book().select().where(Book.title.contains(input('Szukaj tytułu: '))) for book in books: print(f'{book.id} | {book.title}') if not books: self.find_book() while True: try: return Book().get_by_id(int(input('Wybierz książkę'))) except: print('Nie wybrano książki....')
def add_book(): form = BookForm() if form.validate_on_submit(): book = Book() book.name = form.name.data db.session.add(book) db.session.commit() flash(message="Livro Adicionado com sucesso!", category="success") return redirect(url_for("add_book")) return render_template("add_book.html", form=form)
def load_database(iris_native): book_db = data['database'] iris_native.kill(book_db) book_list = [] with open('data/books.csv') as f: lines = f.readlines() for line in lines: book_list.append(line.strip('\n')) for i in range(1, len(book_list)): book = Book() book_info = book_list[i] book_info = book_info.split(',') book.title = book_info[0] book.author = book_info[1] book.publisher = book_info[2] book.page_count = book_info[3] book.pic_url = book_info[4] book.available = True iris_native.set(book.title, book_db, i, "title") iris_native.set(book.author, book_db, i, "author") iris_native.set(book.publisher, book_db, i, "publisher") iris_native.set(book.page_count, book_db, i, "page_count") iris_native.set(book.pic_url, book_db, i, "pic_url") iris_native.set(book.available, book_db, i, "available") print("Loaded books into database")
def create_book(): book_list = book_repository.select_all() for book in book_list: if book.author.name == request.form["author"]: new_book = Book(request.form["title"], book.author) book_repository.save(new_book) return else: new_author = Author(request.form["author"]) author_repository.save(new_author) new_book = Book(request.form["title"], new_author) book_repository.save(new_book) return redirect("/books")
def initialize_book(iris_native, book_db, id): book = Book() book.id = id book.title = iris_native.get(book_db, id, "title") book.author = iris_native.get(book_db, id, "author") book.publisher = iris_native.get(book_db, id, "publisher") book.page_count = iris_native.get(book_db, id, "page_count") book.pic_url = iris_native.get(book_db, id, "pic_url") book.available = iris_native.get(book_db, id, "available") return book
def rating_book_request_impl(args): try: book_name = args['book_name'] author_name = args['author_name'] category_name = args['category_name'] rating = args['rating'] if len(book_name) == 0: raise InvalidBookNameException if rating < 0 or rating > 5: raise InvalidRatingException book = find_book_with_name(book_name) if book is None: book = Book(book_name, author_name, category_name) db.session.add(book) rating = Rating(rating, book) db.session.add(rating) book.ratings.append(rating) db.session.commit() return Response(True, "Book Rating Done", BookSchema().dumps(book).data).output() except Exception as e: return json.dumps({"error": str(e)})
def _fetch_data(self): # We wrap it in a try/except in case it fails try: # Emit that we're fethcing data self.network_state.emit({'state': NetworkState.active}) # Get the data from the server in a GET request r = requests.get(self.url) # Raise if the response code is anything non-200 r.raise_for_status() # Parse the response as JSON js = r.json() # Parse the JSON as a Book self.book = Book.from_json(js["book"]) # And emit the book while saying the fetching is done self.network_state.emit( { "state": NetworkState.done, "data": self.book.__dict__ } ) # If it is not successful... except Exception as e: # ...show the error... print(e) # ...and emit it self.network_state.emit( { "state": NetworkState.error, "error": str(e) } )
def activate_book(book_id): book = Book.get_by_id(book_id) if book is None: return "Book not found" else: book.update("active", True) return "Active"
def delete(self, book_id=None): #delete single book if book_id: #if book not found will cause an error try: book = ndb.Key(urlsafe=book_id).get() #make sure is book assert Book.is_book(book) #remove the book from customer's checked_out #list, if the book is checked out if book.checkedIn == False: Customer.remove_book(book.key) #delete the book ndb.Key(urlsafe=book_id).delete() #HTTP no content self.response.set_status(204) except: #error on not found self.response.set_status(404) return #delete all books else: BookController.delete_all_books() #HTTP no content self.response.set_status(204)
def get_books(self, term, limit=5): current_url = self.url + '/volumes?' + 'q=' + term + '&maxResults=' + str( limit) data = self.client.request('GET', current_url) items = data.get('items') if not items: return [] return [Book(i, data).json() for i, data in enumerate(items)]
def from_json(cls, json_map): if type(json_map) is str: json_map = json.loads(json_map) c = cls(Student.from_json(json_map["student"]), Book.from_json(json_map["book"]), json_map["created_at"], json_map["redeemed"], json_map["redemption_key"]) return c
def post(self, action): # Lets _try_ to add the book and all that. error = False binding = '' condition = '' google_id = self.request.get('google_id') try: binding = self.request.get('binding') condition = self.request.get('condition') except: pass comments = self.request.get('comments') # Quietly ignore errors for now try: price = float(self.request.get('price')) except: price = 0.0 new_book = Book.add_book(google_id) if new_book is None: logging.debug('Error inserting book with google_id of ' + google_id + '!') error = True else: email = self.session.get('email') user = User.get_user(email) print(action) logging.info(action) if action == 'sell': BookListing.sell_book(new_book, user['id'], price, binding, condition, comments) else: BookListing.request_book(new_book, user['id'], price, binding, condition, comments) return self.redirect('/')
def get_mark_dict(mark): result = memcache.get(key=MEM_CACHE_MARK_INFO_KEY_MASK % (mark.category, mark.key.id())) if result is not None: return result events = sorted_history_marks(HistoryEvent.get_by_mark(mark)) persons = sorted_history_marks(HistoryPerson.get_by_mark(mark)) videos = sorted_history_marks(YoutubeVideo.get_by_mark(mark)) channels = filter(partial(is_not, None), (YoutubeChannel.get_by_channel_id(channel_id=channel_id) for channel_id in set([video.channel_id for video in videos]))) books = sorted_history_marks(Book.get_by_mark(mark)) result = { 'text': mark.text.get().dict(), 'events': [event.dict() for event in events], 'persons': [person.dict() for person in persons], 'videos': [video.dict() for video in videos], 'channels': [channel.dict() for channel in channels], 'books': [book.dict() for book in books], 'test': mark.test.get().dict(), 'dependencies': [{ 'id': str(dependency.id()), 'category': str(get_category(dependency)), } for dependency in mark.dependencies], } memcache.add(key=MEM_CACHE_MARK_INFO_KEY_MASK % (mark.category, mark.key.id()), value=result, time=MEM_CACHE_TIME) return result
def find_book(search_param): def where(result, first_name, last_name): if first_name: return result.where((Book.title == search_param) | (Author.first_name == first_name)) if last_name: return result.where((Book.title == search_param) | (Author.last_name == last_name)) return result.where((Book.title == search_param) | (Book.id == int(search_param))) BookAuthor = Book.authors.get_through_model() # 1. zapytanie o nazwisko try: last_name = LastName.get(LastName.name == search_param) except LastName.DoesNotExist: last_name = None # 2. zapytanie o imię try: first_name = FirstName.get(FirstName.name == search_param) except FirstName.DoesNotExist: first_name = None # 3. zapytanie o książkę o tytule lub autorze result = Book.select().join(BookAuthor, JOIN.LEFT_OUTER).join(Author, JOIN.LEFT_OUTER) result = where(result, first_name, last_name) return result
def delete_book(id): book = Book.query.get(id) if book == None: raise NotFoundError('book id not found') db.session.delete(book) db.session.commit() return Book.serialize(book.id, book.book_name, book.author_name)
def _fetch_data(self): # We wrap it in a try/except so the app doesn't crash try: # Emits that fetching is about to occur self.network_state.emit({'state': NetworkState.active}) # Gets the data in a GET request from the server r = requests.get(self.url) # Raises an exception if the response returned a non-200 status code r.raise_for_status() # Parses the response as JSON js = r.json() # Makes a list of books from the JSON self.books = [Book.from_json(j) for j in js["books"]] # And emits that the fetching has been completed, alongside the list of books # These will later be passed to the list model self.network_state.emit({ "state": NetworkState.done, "data": self.books }) # In the case something bad happens... except Exception as e: # ...print the error... print(e) # ...and emit it. self.network_state.emit({ "state": NetworkState.error, "error": str(e) })
def get_books(self, require): db = Data_base().library books = list() for book in Book.objects(title__icontains=require).order_by('-rating'): books.append(self.zip_book(book)) for book in Book.objects( author__icontains=require).order_by('-rating'): books.append(self.zip_book(book)) if books.count(books[-1]) > 1: del books[-1] for book in Book.objects( description__icontains=require).order_by('-rating'): books.append(self.zip_book(book)) if books.count(books[-1]) > 1: del books[-1] return books
def get_all_book(): books = Book.query.all() res = [] for book in books: res.append( Book.serialize(book.id, book.book_name, book.author_name)) return res
def add_book(): if request.method == "GET": return render_template("books/add.html") book_title = request.form.get("book-title") book_author = request.form.get("book-author") if not book_title: raise BadRequest("Field 'Title' is required!") # raise BadRequest("Field 'book-title' is required!") elif not book_author: raise BadRequest("Field 'Author' is required!") book = Book(title=book_title, author=book_author) db.session.add(book) try: db.session.commit() except IntegrityError: log.exception("Couldn't add book, git integrity error") db.session.rollback() raise BadRequest( "Error adding new book, probably the title is not unique") except DatabaseError: log.exception("Could not add book, got database error") db.session.rollback() raise InternalServerError("Error adding new book") url = url_for("books_app.details", book_id=book.id) return redirect(url)
def borrow_book(self, title, user): """ 返回1表示借阅成功 """ book = Book.find_one(title=title) bs = user.borrowed_books() if book in bs: log("Borrow: 无法重复借阅同一名字的书") return 0 if book is not None and book.in_stock(): log("Borrow: {}有库存".format(title)) new_borrow = Borrow() if user.card_id == "None": log("该用户没有借书证") return 0 new_borrow.card_id = user.card_id new_borrow.book_id = book.id new_borrow.return_date = None try: book.stock_minus_one() except Exception: # 库存数不足 log("借书失败") return 0 else: new_borrow.save() log("Borrow: 借书成功, 书名:{}".format(book.title)) return 1 else: log("Borrow: 借书失败: 书籍不存在或库存不足") return 0
def convert_json_to_POJO_list(booksJson): matchedBooks = [] if booksJson['totalItems'] != 0: for book in booksJson['items']: b = Book() addBookProperty(book, b, 'isbn', 'volumeInfo', 'industryIdentifiers') addBookProperty(book, b, 'authors', 'volumeInfo', 'authors') addBookProperty(book, b, 'title', 'volumeInfo', 'title') addBookProperty(book, b, 'id', 'id') addBookProperty(book, b, 'description', 'volumeInfo', 'description') addBookProperty(book, b, 'pageCount', 'volumeInfo', 'pageCount') addBookProperty(book, b, 'rating', 'volumeInfo', 'averageRating') addBookProperty(book, b, 'thumbnail', 'volumeInfo', 'imageLinks', 'thumbnail') addBookProperty(book, b, 'publishedDate', 'volumeInfo', 'publishedDate') addBookProperty(book, b, 'publisher', 'volumeInfo', 'publisher') addBookProperty(book, b, 'language', 'volumeInfo', 'language') addBookProperty(book, b, 'previewLink', 'volumeInfo', 'previewLink') addBookProperty(book, b, 'country', 'saleInfo', 'country') b.add('availableQuantity', 2) matchedBooks.append(b) return matchedBooks
# -*- coding: utf-8 -*- from models.book import Book book1 = Book() book1.title = "Code Complete" book1.order = 9 book1.rating = 5 book1.link = 'http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670' book1.review = 'Code complete is a good read for anyone in the software industry. It was a really long read, but some chapters were pretty basic so you will most likey skimming through them unless you are new to development. It makes some really good points about the entire software life cycle and statistics to back up his viewpoints.' book1.put() book2 = Book() book2.title = 'Effective Programming: More Than Writing Code' book2.order = 8 book2.rating = 4 book2.link = 'http://www.amazon.com/Effective-Programming-More-Writing-ebook/dp/B008HUMTO0' book2.review = "This is really a compilation of the blog posts of Jeff Atwood. I mostly bought it because it wasn't that expensive and it made for easy reading on the train without an internet connection. It is still a good read, but you can pretty much read his blog archive and get the same gist." book2.put() book3 = Book() book3.title = 'Head First Design Patterns' book3.order = 6 book3.rating = 4 book3.review = "A good book that talks about disign patterns you should use and how to identify them. Most of the patterns used are applicable to traditional programming languages such as c++, Java, and .Net. If you are working in more modern scripting languages then you might not get as much use out of it." book3.link='http://www.amazon.com/Head-First-Design-Patterns-ebook/dp/B00AA36RZY/' book3.put() book4 = Book() book4.title = "First, Break All the Rules: What the world's Greatest Managers Do Differently" book4.link = 'http://www.amazon.com/First-Break-All-Rules-Differently/dp/0684852861' book4.order = 1
def get(self): books = Book.all().order('-order') self.response.out.write(simplejson.dumps([m.to_dict() for m in books]))