def put(self, idd): data = self.__parse_request__() exists = BookModel.find_by_id(idd) if not exists: return { 'message': "A book with ['id': {}] not found".format(idd) }, 404 authors = [] exists.author = [] exists.save_to_db() a = AuthorModel.find_by_name(data.get('author_name')) if a: authors.append(a) else: new_author = AuthorModel(data.get('author_name'), data.get('author_bd'), data.get('author_city'), data.get('author_country')) authors.append(new_author) new_author.save_to_db() exists.delete_from_db() new_book = BookModel(data.get('isbn'), data.get('name'), authors, data.get('genre'), data.get('year'), data.get('editorial'), data.get('language'), data.get('price'), data.get('synopsis'), data.get('description'), data.get('num_pages'), data.get('cover_type'), data.get('num_sales'), data.get('total_available'), data.get('cover_image_url'), data.get('back_cover_image_url')) new_book.id = idd new_book.save_to_db() return new_book.json(), 200
def post(self): # Create a new author with the data passed to us. parser = reqparse.RequestParser( ) # create parameters parser from request # define all input parameters need and its type parser.add_argument('name', type=str, required=True, help="This field cannot be left blanck") parser.add_argument('birth_date', type=str, required=True, help="This field cannot be left blanck") parser.add_argument('city', type=str, required=True, help="This field cannot be left blanck") parser.add_argument('country', type=str, required=True, help="This field cannot be left blanck") data = parser.parse_args() exists = AuthorModel.find_by_name(data.name) if exists: return {'message': "Author already exists"}, 409 # The ID is the following to the last one new_author = AuthorModel(data.get('name'), data.get('birth_date'), data.get('city'), data.get('country')) new_author.save_to_db() return {'message': "OK"}, 201
def put(self, idd): # Create a new author with the data passed to us. parser = reqparse.RequestParser( ) # create parameters parser from request # define all input parameters need and its type parser.add_argument('name', type=str, required=True, help="This field cannot be left blanck") parser.add_argument( 'birth_date', type=lambda s: datetime.datetime.strptime(s, '%Y-%m-%d'), required=True, help="This field cannot be left blanck") parser.add_argument('city', type=str, required=True, help="This field cannot be left blanck") parser.add_argument('country', type=str, required=True, help="This field cannot be left blanck") data = parser.parse_args() author = AuthorModel.find_by_id(idd) if author: author.delete_from_db() new_author = AuthorModel(data.get('name'), data.get('birth_date'), data.get('city'), data.get('country')) new_author.save_to_db() return {'message': "Author modified"}, 201 return {'message': "Author with id [{}] Not found".format(idd)}, 409
def post(self): data = self.__parse_request__() exists = BookModel.find_by_name(data.get('name')) if exists: return { 'message': "A book with ['name': {}] already exists".format(exists.name) }, 409 authors = [] a = AuthorModel.find_by_name(data.get('author_name')) if a: authors.append(a) else: new_author = AuthorModel(data.get('author_name'), data.get('author_bd'), data.get('author_city'), data.get('author_country')) authors.append(new_author) new_author.save_to_db() new_book = BookModel(data.get('isbn'), data.get('name'), authors, data.get('genre'), data.get('year'), data.get('editorial'), data.get('language'), data.get('price'), data.get('synopsis'), data.get('description'), data.get('num_pages'), data.get('cover_type'), data.get('num_sales'), data.get('total_available'), data.get('cover_image_url'), data.get('back_cover_image_url')) new_book.save_to_db() return new_book.json(), 200
def get(self, author_name): '''Get books by author id''' author = AuthorModel.find_by_name(author_name) if not author: return [], 404 try: books = AuthorModel.get_all_books_from_author(author.id) except Exception as e: return [], 404 book_list = [book.json() for book in books] return book_list, 200
def post(self, name): if _author(name): return {"message": "author with that name already exists"}, 409 data = Author.parser.parse_args() author = AuthorModel(name) try: author.save_to_db() except Exception: return {'message': 'can not save the note'}, 500 return author.json(), 201
def get(self): data = self.__parse_request__() query = data.get('name') books = [(a.json()['book']['name'].lower(), 'book') for a in BookModel.query.all()] authors = [(a.json()['name'].lower(), 'author') for a in AuthorModel.query.all()] isbn = [(a.json()['book']['ISBN'], 'isbn') for a in BookModel.query.all()] repo = books + authors + isbn books = [] for i, j in repo: if str(query).lower() in str(i): if j == 'book': b = BookModel.query.filter( BookModel.name.like(i)).first().json() if b not in books: books.append(b) elif j == 'isbn': b = BookModel.query.filter( BookModel.isbn.like(i)).first().json() if b not in books: books.append(b) else: author = AuthorModel.find_by_name(i.title()) for book in BookModel.query: for a in book.author: if a == author: b = book.json() if b not in books: books.append(b) return {'books': books}, 200
def delete(self, name): authors = AuthorModel.find_by_name(name) for author in authors: if author.name == name: author.delete_from_db() return {'message': 'Author deleted.'} return {'message': f"Author '{name}' not found."}, 404
def put(self, title): note = NoteModel.filter_by_title(title) data = Note.parser.parse_args() author = AuthorModel.filter_by_name(data['author']) if author is None: return {'message': 'This author is not registered yet'}, 404 if note is None: note = NoteModel(title, **data) else: Note.parser.add_argument('new_title', dest='title') data = Note.parser.parse_args() note.title = data['title'] note.author_id = author.id note.note = data['note'] note.updated_date = datetime.datetime.now() try: note.save_to_db() except Exception: return {'message': 'can not save the note'}, 500 return note.json(), 200
def post(self): args = self.reqparse.parse_args() author = AuthorModel(args.author) db.session.add(author) db.session.commit() res = AuthorSchema().dump(author).data return res, 201
def json(self): author = AuthorModel.filter_by_id(self.author_id) if author is not None: return { "Title": self.title, "Author": author.name, "Note": self.note } return {"message: "}
def start(): """ Method that performs the persistence of authors contained in a csv file. """ try: with open('authors.csv', 'r') as file: authors = csv.DictReader(file) # lambda that returns Author Model object if it doesn't # already exist in the bank item = lambda item: AuthorModel(name=(item['name'])) \ if not AuthorModel.get_by_name(item['name']) else None objects = [] for i in authors: author = item(i) objects.append(author) if author else None db.session.add_all(objects) db.session.commit() except Exception as e: return e print('Persistence of authors completed')
def get(self, id): """GET request that deals with requests that look for a author by id""" # Call the model Author = AuthorModel.find_by_id(id) # If exists if Author: return Author.json() # If doesn't exists return {'message': 'Author not found'}, 404
def put(self, name): """PUT request that creates an author, provided a name and description, image_url, wiki_url""" # Parse the application/json data data = Author.parser.parse_args() # Request to the model to find the author author = AuthorModel.find_by_name(name) # If found if author: # We update its variables author.name = data['name'] author.description = data['description'] author.image_url = data['image_url'] author.wiki_url = data['wiki_url'] else: # Else we create it author = AuthorModel(**data) # Then we save author.save_to_db() # We return the updated author in json return author.json()
def post(self, name): """POST request that creates an author, provided a name and description, image_url, wiki_url""" # Request to the model and if found if AuthorModel.find_by_name(name): # Return meessage that author exists return { 'message': "An Author with name '{}' already exists.".format(name) }, 400 # Parse the application/json data data = Author.parser.parse_args() # We pass the arguments to the model author = AuthorModel(name, **data) # Try to save try: author.save_to_db() except: # if error return {"message": "An error occurred inserting the Author."}, 500 # Return a json of the created author return author.json(), 201
def post(self): """POST request that creates an author, provided a name and description, image_url, wiki_url""" # Parse the application/json data data = Author.parser.parse_args() # Look if we find the author by its name if AuthorModel.find_by_name(data['name']): return { 'message': "An author with name '{}' already exists.".format(data['name']) }, 400 # If user doesn't exists then we create it author = AuthorModel(**data) # we try push and commit try: author.save_to_db() except: #if error return {"message": "An error occurred inserting the author."}, 500 # We return a json of the author return author.json(), 201
def add_book(self): b = books[0] authors = [] author = b[2][0] author = AuthorModel(author[0], author[1], author[2], author[3]) authors.append(author) book = BookModel(b[0], b[1], authors, b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]) db.session.add(author) db.session.add(book) db.session.commit()
def put(self, book_id, author, title, date, genre): '''Update a book by book id''' cur_book = BookModel.find_by_id(book_id) if not cur_book: return {'message' : 'book with id {} is not found.'.format(book_id)}, 404 new_author = AuthorModel.search_and_add_author(author) new_genre = GenreModel.search_and_add_genre(genre) new_date = DateRead.read_date(date) cur_book = BookModel.update_book(book_id, title, new_author, new_date, new_genre) return cur_book.json(), 200
def get(self, name): """GET request that deals with requests that look for a author provided its name""" # Request to the model Author = AuthorModel.find_by_name(name) # if found if Author: # Return a json return Author.json() # if not return {'message': 'Author not found'}, 404
def post(self, name): for author in AuthorModel.find_by_name(name): if author.name == name: return {'message': f'User: {name} already exists.'} author = AuthorModel(name) author.save_to_db() return author.json(), 201
def post(self): items = self.arguments.parse_args() authors = [ast.literal_eval(authors) for authors in items['authors']] authors_obj = [] for author in authors: if author.get('middlename'): authors_obj.append(AuthorModel(**author)) else: author['middlename'] = None authors_obj.append(AuthorModel(**author)) items.pop('authors') book_obj = BookModel(**items) if book_obj.find(book_obj.title): book_obj = book_obj.find(book_obj.title) return {'book': book_obj.json()}, 409 else: book_obj.save() for author_obj in authors_obj: if not author_obj.find(author_obj.firstname): author_obj.save() else: author_obj = author_obj.find(author_obj.firstname) book_author_obj = BookAuthorModel(book_obj, author_obj) if not book_author_obj.find(): book_author_obj.save() return {'book': book_obj.json()}, 200
def post(self, title, author, date, genre): '''Add a new book''' cur_author = AuthorModel.search_and_add_author(author) cur_genre = GenreModel.search_and_add_genre(genre) release_date = DateRead.read_date(date) #create the new book, add into db new_book = BookModel(title, cur_author.id, release_date, cur_genre) new_book.save_to_db() if not new_book: return {"message" : "add book error"}, 403 return new_book.json(), 201
def delete(self, id_author): author = AuthorModel.find(field='id_author', key=id_author) if author: try: author.delete() except: return { 'mensage': 'An error ocurred trying to delete author.' }, 500 return {'mensage': 'Autor deletado'} return {'mensage': 'Book not found'}, 404
def get(self): reqdata = NewsList.parser.parse_args() if reqdata['search_key'] is None: return [n.json() for n in NewsModel.find_all()] found_news = NewsModel.find_any(reqdata['search_key']) authors_news = [] for author in AuthorModel.find_by_name(reqdata['search_key']): authors_news += NewsModel.find_by_author(author.id) for news in authors_news: if news in found_news: found_news.remove(found_news.index(news)) return [n.json() for n in found_news + authors_news]
def post(self, title): if NoteModel.filter_by_title(title): return {"message": "note with that title already exists"}, 409 data = Note.parser.parse_args() author = AuthorModel.filter_by_name(data['author']) if author.id is None: return {'message': 'This author is not registered yet'}, 404 note = NoteModel(title, author.id, data['note']) try: note.save_to_db() except Exception: return {'message': 'can not save the note'}, 500 return note.json(), 201
def delete(self, id): """DELETE request that deals with the deletion of an author provided a certain id""" # Call the model Author = AuthorModel.find_by_id(id) # If exists if Author: try: # We try to delete Author.delete_from_db() return {'message': 'Author deleted'} except: return { 'message': 'ERROR : During the deletion of author : {}'.foramt(id) } else: # In case we don't found the author return {'message': 'Author not found'}, 404
def delete(self, id): """DELETE request that deals with the deletion of an author provided an authorId""" # We look for the Author provided an id Author = AuthorModel.find_by_id(id) # If exists if Author: try: # We try to delete it from the database Author.delete_from_db() return {'message': 'Author deleted'} except: # If error return { 'message': 'The author has relations you might want to delete the books that belongs to him first.' } else: # If he doesn't exist return {'message': 'Author not found'}, 404
def post(self): data = self.arguments.parse_args() author = AuthorModel(**data) author_find = author.find(author.firstname) if author_find: #return {"mensage": "Book id '{}' already exists.".format(data.title)}, 200 return author_find.json(), 409 else: try: author.save() except: return { 'mensage': 'An internal error ocurred trying to save author.' }, 500 return author.json()
def put(self, id_author): data = Author.arguments.parse_args() data = AuthorModel(id_author, **data) find_author = AuthorModel.find(id_author) if find_author: find_author.update(**data) find_author.save() return find_author.json(), 200 #ok new_author = AuthorModel(id_author, **data) try: new_author.save() except: return { 'mensage': 'An internal error ocurred trying to save author.' }, 500 return find_author.json()
def post(self, id): """POST request that deals with the creation of an a new author""" if AuthorModel.find_by_id(id): return { 'message': "An Author with id '{}' already exists.".format(id) }, 400 # Parse the application/json data data = Author.parser.parse_args() # Call the model author = AuthorModel(id, **data) try: # Try to save and commit the author author.save_to_db() except: # If it breaks return {"message": "An error occurred inserting the Author."}, 500 # Return the json of the author return author.json(), 201