def seed_db(): from models.Book import Book from models.User import User from main import bcrypt from faker import Faker import random faker = Faker() users = [] for i in range(5): user = User() user.email = f"test{i}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") db.session.add(user) users.append(user) db.session.commit() for i in range(20): book = Book() book.title = faker.catch_phrase() book.user_id = random.choice(users).id db.session.add(book) db.session.commit() print("Tables seeded")
def seed_db(): from models.Book import Book # Import the book model from models.User import User # User model from main import bcrypt # Hashing module from faker import Faker # Import the faker module import random faker = Faker() # Create an instance of faker users = [] # Initializing an empty list # Creating 5 users and appending them to the users list for i in range(5): user = User() user.email = f"test{i}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") db.session.add(user) users.append(user) db.session.commit() for i in range(20): # 20 book = Book() # New instance of book book.title = faker.catch_phrase() # Add a title book.user_id = random.choice( users).id # Choosing a random user to assign the book to db.session.add(book) # add the book to the db session db.session.commit() # Commit all the books to the db print("Tables seeded")
def main(): start = Location(100, 200) end = Location(200, 200) anna = HouseWife("Anna", end, 1000, "0") ant25 = Plane("ANT25", 10000, 10) ant20 = Plane("ant20", 5000, 10) inter_city = Train("InterCity", 15) chs2 = Train("ChS2", 15) sprinter = Bus("Sprinter", 200) double_decker = Bus("Double Decker", 100) delivery_date = Date(2019, 4, 21) urk_air_transport = PlaneDelivery("SlavaUkraini", 100, 1220, start, end, ant25, delivery_date, anna) pl_air_transport = PlaneDelivery("SmertVorogam", 100, 200, start, end, ant20, Date(2019, 4, 22), anna) urk_railway = TrainDelivery("UkrRailway", 1000, 120, start, end, inter_city, Date(2020, 4, 21), anna) pl_railway = TrainDelivery("PlRailway", 100, 109, start, end, chs2, Date(2019, 5, 27), anna) fed_ex = BusDelivery("FedEx", 100, 1000, start, end, sprinter, Date(2025, 4, 21), anna) dhl = BusDelivery("dhl", 200, 57, start, end, double_decker, Date(2030, 1, 2), anna) taras_bulba = Book("Taras Bulba", 500, 400, "Nikolya Gogol", urk_air_transport) kobzar = Book("Kobzar", 700, 1000, "Taras Shevchenko", pl_air_transport) garry_potter = Book("Garry Potter", 100, 250, "Joah Rouling", urk_railway) pro_retina_13 = MacBook("Pro Retina 13", 1250, 13, 13, urk_railway) pro_retina_15 = MacBook("Pro Retina 15", 2250, 15, 17, fed_ex) air_retina_13 = MacBook("Air Retina 13", 1200, 13, 13, pl_railway) g403 = ComputerMouse("Logitech g403", 60, 5, 2, dhl) netscroll120 = ComputerMouse("Genius netscroll 120", 5, 2, 1, dhl) razer_champion = ComputerMouse("Razor Champion", 100, 10, 2, dhl) marta = HouseWife("Marta", end, 1000, "BOOKS") nina = HouseWife("Nina", end, 100, "PANS") amazon_catalog = [taras_bulba, kobzar, pro_retina_13, g403, netscroll120] amazon_clients = [marta, nina] amazon = Shop("Amazon", "amazon.com", amazon_catalog) amazon_manager = ShopManager(amazon_clients, amazon)
def book_create(user=None): # Create a new book data = book_schema.load(request.json) new_book = Book() new_book.title = data["title"] user.books.append(new_book) db.session.commit() return jsonify(books_schema.dump(Book.query.all()))
def book_create(): # Create a new book book_fields = books_schema.load(request.json) new_book = Book() new_book.title = book_fields['title'] db.session.add(new_book) db.session.commit() return jsonify(books_schema.dump(new_book))
def test_fetch_all(self): book = Book("From earth to moon", "Jules Vern", "20-9-2020", "SDFD") self.bookDAO.add_book(book) book = Book("20 thousand leagues", "Jules Vern", "20-9-2021", "SDsFD") self.bookDAO.add_book(book) books = self.bookDAO.fetch_all() assert (books != None) assert (len(books) == 2) for book in books: print(("Title: {0}, Author: {1}, Date: {2}, ISBN: {3}".format( book.title, book.author, book.year, book.isbn)))
def seed_db(): from models.Book import Book from faker import Faker faker = Faker() for i in range(20): book = Book() book.title = faker.catch_phrase() db.session.add(book) db.session.commit() print("Tables seeded!")
def seed_db(): from models.Book import Book from faker import Faker faker = Faker() for i in range(10): book = Book() book.title = faker.catch_phrase() db.session.add(book) print(f"{i+1} book record(s) created") db.session.commit() print("Tables seeded")
def book_create(user): #Create a new book book_fields = book_schema.load(request.json) new_book = Book() new_book.title = book_fields["title"] user.books.append(new_book) db.session.commit() return jsonify(book_schema.dump(new_book))
def post(self): jinja = jinja2.get_jinja2(app=self.app) user = users.get_current_user() if user: if self.request.get('deleting'): book_id = self.request.get('book_id') book_key = ndb.Key(Book, int(book_id)) book = book_key.get() if book.user == user.email(): book_key.delete() # Para darle tiempo al recargar a que haya borrado el libro time.sleep(1) self.redirect('/') elif self.request.get('title'): src = self.request.get('src') title = self.request.get('title') description = self.request.get('description') category = self.request.get('category') book = Book(title=title, description=description, category=category, user=user.email()) book.src = images.resize(src, 120, 240) book.put() # Para darle tiempo al recargar a que coja el nuevo libro time.sleep(1) self.redirect('/') else: template_values = {'users': users} self.response.write( jinja.render_template("add_book.html", **template_values)) else: template_values = { 'login_url': users.create_login_url('/'), 'users': users } self.response.out.write( jinja.render_template("sign_in.html", **template_values))
def post(self): try: req = request.get_json(force=True) data = BookValidator().validate(req) resource = Book() query = resource.add(data) return BookDetail().get(query.id) except Exception as ex: resp = jsonify({"error": str(ex)}) resp.status_code = 403 return resp
def book_create(user=None): # Define the create function. user=none to use the decorator book_fieds = book_schema.load(request.json) # Deserializing the json into something that can be used # user_id = get_jwt_identity() # Get identity returns the userid from the JWT # user = User.query.get(user_id) # Return the user from querying the DB with the DB # if not user: # If no user then return the id # return abort(401, description="Invalid user") new_book = Book() # Creating a new instance of book new_book.title = book_fieds["title"] # Update the title user.books.append(new_book) # Add this book to the the user who created it db.session.commit() # Commit the transaction return jsonify(book_schema.dump(new_book)) # Return the json format of the book
def map_to_model(entity: dict): model = Book() model.id = str(entity['_id']) model.title = entity['title'] model.description = entity['description'] model.cover_url = entity['coverUrl'] model.author_id = entity['author_id'] model.updated = entity['updated'] model.created = entity['created'] return model
def book_create(): #Create a new book book_fields = book_schema.load(request.json) if "title" not in book_fields.keys(): return abort(400) new_book = Book() new_book.title = book_fields["title"] db.session.add(new_book) db.session.commit() return jsonify(book_schema.dump(new_book))
def get(self): reload(sys) sys.setdefaultencoding("utf-8") jinja = jinja2.get_jinja2(app=self.app) filtered = False if self.request.get('category') or self.request.get('text_filter'): filtered = True else: filtered = False if self.request.get('category'): books = Book.query(Book.category == self.request.get('category')) else: books = Book.query() text_filter = self.request.get('text_filter') book_list = [] for book in books: if text_filter.lower() in book.title.lower(): votes = Vote.query(Vote.book_id == book.key.id()) ratings = [] for vote in votes: ratings.append(vote.stars) if ratings: mean = float(sum(ratings)) / len(ratings) stars = round(mean * 2) / 2 else: stars = 0 book_list.append({ 'id': book.key.id(), 'src': book.src, 'title': book.title, 'stars': stars, 'user': book.user, 'num_votes': len(ratings) }) template_values = {'book_cards': book_list, 'users': users, 'filtered': filtered, 'category_filter': self.request.get('category'), 'text_filter': self.request.get('text_filter')} self.response.write(jinja.render_template("index.html", **template_values))
def add_books(self): books = self.books_service.get_books("") print('\nLista Carti: ') self.show_all_books() authors = self.authors_service.get_authors("") print('\nLista Autori: ') self.show_all_authors() book_isbn = input("Introduceti ISBN-ul cartii: ") if book_isbn in [book['ISBN'] for book in books]: print('\nISBN deja existent!\n') return # extracted this method because of the similarity between add_books and update_books validated_inputs = self.validate_book_inputs(authors) if validated_inputs is None: return result = self.books_service.add_book( Book(book_isbn, validated_inputs['book_title'], validated_inputs['book_nr_of_pages'], validated_inputs['book_type'], validated_inputs['book_description']), validated_inputs['book_authors']) if result['success'] is False: print('\nEroare -->', result['type']) return if result['success']: print('\nOperatie efectuata cu succes!') self.show_all_books()
def main(): [ADD, LIST, TOGGLE_READ, DELETE, QUIT] = ['a', 'l', 'r', 'd', 'q'] chosenDb, db = set_data_store( input(""" Choose type of data store: 1. Sqlite Database 2. File Storage Press any other key to QUIT Choice:""")) if not chosenDb: return print(db) user_input = menu() while user_input != QUIT: if user_input == ADD: book, author = getBookNameAndAuthor() db.add_book(Book(book, author)) elif user_input == LIST: print(db.list_books()) elif user_input == TOGGLE_READ: book, author = getBookNameAndAuthor() db.mark_read(book, author) elif user_input == DELETE: book, author = getBookNameAndAuthor() db.delete_book(book, author) user_input = menu()
def update_books(self): authors = self.authors_service.get_authors("") print('\nLista Autori: ') self.show_all_authors() books = self.books_service.get_books("") print('\nLista Carti: ') self.show_all_books() book_isbn = input("Introduceti ISBN-ul cartii: ") if book_isbn not in [book['ISBN'] for book in books]: print('\nISBN inexistent!\n') return validated_inputs = self.validate_book_inputs(authors) if validated_inputs is None: return result = self.books_service.update_book( Book(book_isbn, validated_inputs['book_title'], validated_inputs['book_nr_of_pages'], validated_inputs['book_type'], validated_inputs['book_description']), validated_inputs['book_authors']) if result['success'] is False: print('\nOperatie esuata') return if result['success']: print('\nOperatie efectuata cu succes!') self.show_all_books()
def test_add_book(self): book = Book("From earth to moon", "Jules Vern", "20-9-2020", "SDFD") self.bookDAO.add_book(book) SQL = "SELECT * FROM store" rows = self.bookDAO.connection.execute_sql(SQL) assert (rows != None) assert (len(rows) == 1)
def _db_book_to_model(book): date_added = book[0] isbn = book[1] url = book[2] title = book[3] authors = book[4] subjects = book[5] subject_places = book[6] subject_people = book[7] subject_times = book[8] publishers = book[9] publish_places = book[10] publish_date = book[11] cover_url = book[12] number_of_pages = book[13] weight = book[14] return Book( date_added=date_added, isbn=isbn, url=url, title=title, authors=authors, subjects=subjects, subject_places=subject_places, subject_people=subject_people, subject_times=subject_times, publishers=publishers, publish_places=publish_places, publish_date=publish_date, cover_url=cover_url, number_of_pages=number_of_pages, weight=weight, )
def fetch_all(self): books = [] SQL = "SELECT * FROM store" rows = self.connection.execute_sql(SQL) for row in rows: books.append(Book(row[0], row[1], row[2], row[3])) return books
def show(book_id): schema = BookSchema() book = Book.get(id=book_id) if not book: abort(404) return schema.dumps(book)
def insert_current(self): book = Book(self._titleText.get("1.0", 'end-1c'), self._authorText.get("1.0", 'end-1c'), self._yearText.get("1.0", 'end-1c'), self._isbnText.get("1.0", 'end-1c')) self._books.append(book) self.update_listbox_items(self._books) self.update_listeners('INSERT', book)
def update_selected(self, index): book = Book(self._titleText.get("1.0", 'end-1c'), self._authorText.get("1.0", 'end-1c'), self._yearText.get("1.0", 'end-1c'), self._isbnText.get("1.0", 'end-1c')) self._books[index] = book self.update_listbox_items(self._books) self.update_listeners('UPDATE', book)
def book_create(): #Create a new book book_fields = book_schema.load(request.json) user_id = get_jwt_identity() user = User.query.get(user_id) if not user: return abort(401, description="Invalid user") new_book = Book() new_book.title = book_fields["title"] user.books.append(new_book) db.session.commit() return jsonify(book_schema.dump(new_book))
def delete_review(book_id, review_id): schema = BookSchema() book = Book.get(id=book_id) review = Review.get(id=review_id) review.delete() db.commit() return schema.dumps(book)
def delete(book_id): book = Book.get(id=book_id) if not book: abort(404) book.delete() db.commit() return '', 204
def instantiate_book(self, found_book_info): new_book = Book(found_book_info["title"], found_book_info["author"], found_book_info["year"]) new_book.id = str(found_book_info["_id"]) new_book.isAvailable = found_book_info["isAvailable"] new_book.waitingList = found_book_info["waitingList"] new_book.description = found_book_info["description"] new_book.publisher = found_book_info["publisher"] return new_book
def get_all_book(): con = __open_db() cursor = con.cursor() result_set = cursor.execute('SELECT * FROM book') result = [] for isbn, title, authors, publisher, publish_year in result_set: result.append(Book(isbn, title, authors, publisher, publish_year)) __close_db(cursor, con) return result
def get_book(isbn): # Get book by ISBN (Primary Key) con = __open_db() cursor = con.cursor() result_set = cursor.execute('SELECT * FROM book WHERE isbn=?', [isbn]) result = [] for isbn, title, authors, publisher, publish_year in result_set: result.append(Book(isbn, title, authors, publisher, publish_year)) __close_db(cursor, con) return result
def search(self, book): books = [] SQL = "SELECT * FROM store WHERE " values = [ value for value in book.__dict__.values() if value ] for property in book.__dict__.keys(): if (book.__dict__[property]): SQL += property + " LIKE '%" + book.__dict__[property] + "%' AND " if len(values) > 0: SQL += ' 1=1;' rows = self.connection.execute_sql(SQL) for row in rows: books.append(Book(row[0], row[1], row[2], row[3])) return books