def setUp(self): # Create books list and save it self.books = [ Book(author='J.R.R. Tolkien', title='The Hobbit'), Book(author='Fyodor Dostoevsky', title='Crime and Punishment'), Book(author='Richard Phillips Feynman', title="Surely You're Joking, Mr. Feynman"), Book(author='Michio Kaku', title='Physics of the Impossible'), Book(author='Cixin Liu', title='The Three-Body Problem'), ] [book.save() for book in self.books] # Create a dictionary contain n number of random reviews bound to book self.reviews = dict() for n, book in enumerate(self.books, start=1): self.reviews[str(book)] = { 'avg': 0, 'reviews': list(), 'number_of_reviews': int(), } self.reviews[str(book)]['number_of_reviews'] = n for _ in range(n): rate = random.randrange(0, 5) review = Review(book=book, review=rate) review.save() self.reviews[str(book)]['reviews'].append(review) self.reviews[str(book)]['avg'] += rate self.reviews[str(book)]['avg'] /= n
def put(self, book_id): """Function serving edit book api endpoint""" current_user = get_jwt_identity() user = User.get_user_by_username(current_user) if validate_arg(book_id): return validate_arg(book_id) if user: if user.is_admin: book = Book.get_book_by_id(book_id) if book: data = request.get_json(self) if validate_book(data): return Response(json.dumps(validate_book(data)), status=403) book.title = data['title'] book.author = data['author'] book.isbn = data['isbn'] book.publisher = data['publisher'] book.quantity = data['quantity'] book.save() book = Book.get_book_by_id(book_id) return Response(json.dumps({ "Message": "Book updated successfully", "Book": book.serialize }), status=200) return Response(json.dumps({"Message": "Book does not exist"}), status=404) return Response(json.dumps({"Message": "User not an admin"}), status=401) return Response(json.dumps({"Message": "User does not exist"}), status=404)
def save(self, validated_data): try: book_object = Book(**validated_data) book_object.save() book_serialized = BookSerializer(validated_data) return book_serialized.data except Exception as err: print(err) return {}
def delete(self, book_id): """Function to delete a book""" data = Book.getBook(book_id) if not data: return {'Error': 'Book Does not Exist'} res = jsonify(Book.deleteBook(book_id)) res.status_code = 200 return res
def post(self): """ Function to add a book :return: """ data = request.get_json(self) try: schema = { "type": "object", "properties": { "title": {"type": "string"}, "desciption": {"type": "string"}, "author": {"type": "string"} }, "required": ["description", "title", "author"] } validate(data, schema) valid_book = BookSchema().load(data) if not valid_book.data["title"]: return {'Error': 'Book must have a Title'}, 403 elif valid_book.data["title"].isspace(): return {'Error': 'Book must have a Title'}, 403 elif valid_book.data["description"].isspace(): return {'Error': 'Book must have a Description'}, 403 elif not valid_book.data["description"]: return {'Error': 'Book must have a Description'}, 403 elif not valid_book.data["author"]: return {'Error': 'Book must have an Author'}, 403 elif valid_book.data["author"].isspace(): return {'Error': 'Book must have a Author'}, 403 else: new_book = Book(title=valid_book.data["title"], description=valid_book.data["description"], author=valid_book.data["author"]) new_book.createBook() return jsonify({'Success': 'Book added successfully.'}) except: return {"Error": "Missing or wrong inputs"}, 400
def setUp(self): self.url = reverse('book-list') self.books = [ Book(author='J.R.R. Tolkien', title='The Hobbit'), Book(author='Fyodor Dostoevsky', title='Crime and Punishment'), Book(author='Richard Phillips Feynman', title="Surely You're Joking, Mr. Feynman"), Book(author='Michio Kaku', title='Physics of the Impossible'), Book(author='Cixin Liu', title='The Three-Body Problem'), ] for book in self.books: book.save() Review.objects.create(book=book, review=2)
def post(self): args = self.parser.parse_args() cover_image_name, cover_image = args.get( 'cover_image_filename'), args['cover_image'] book = Book(args['name'], args["authors"]) if cover_image_name and cover_image: book.cover_image = decode_image( name=secure_filename(cover_image_name), data64=cover_image, max_length=255) book.save() return marshal(book, self.fields, envelope='book'), 200
def put(self, book_id): """Function serving return book api endpoint""" current_user = get_jwt_identity() user = User.get_user_by_username(current_user) if user: if validate_arg(book_id): return Response(json.dumps(validate_book(data)), status=403) book = Book.get_book_by_id(book_id) if book: to_return = BorrowBook.query.filter_by(user_id=user.id, book_id=book.id, returned=False).first() if to_return: to_return.returned = True to_return.date_returned = datetime.now() to_return.save() book.quantity += 1 book.save() return Response(json.dumps( {"Message": "Book returned successfully"}), status=200) return Response(json.dumps( {"Message": "You had not borrowed this book"}), status=403) return Response(json.dumps({"Message": "Book does not exist"}), status=404) return Response(json.dumps({"Message": "User does not exist"}), status=404)
def delete(self, book_id): """Function serving delete book api endpoint""" current_user = get_jwt_identity() user = User.get_user_by_username(current_user) if validate_arg(book_id): return validate_arg(book_id) if user: if user.is_admin: book = Book.get_book_by_id(book_id) if book: borrowed = BorrowBook.query.filter_by( book_id=book_id).first() if borrowed: return Response(json.dumps( {"Message": "Book has been borrowed"}), status=403) else: book.delete() return Response(json.dumps( {"Message": "Book deleted successfully"}), status=200) return Response(json.dumps({"Message": "Book doesn't exist"}), status=404) return Response(json.dumps({"Message": "User not an admin"}), status=401) return Response(json.dumps({"Message": "User does not exist"}), status=404)
def new_book(new_user): new_user.save() return Book( name='Advanced Cloud Native Go', description='Lorem ipsum is the best placeholder text', owner=new_user )
def post(self, book_id): """Function serving borrow book api endpoint""" current_user = get_jwt_identity() user = User.get_user_by_username(current_user) if user: if validate_arg(book_id): return Response(json.dumps(validate_book(data)), status=400) book = Book.get_book_by_id(book_id) if book: if book.quantity == 0: return Response(json.dumps( {"Message": "Book not available to borrow"}), status=404) borrowed = BorrowBook.query.filter_by(user_id=user.id, book_id=book.id, returned=False).first() if borrowed: return Response(json.dumps( {"Message": "Already borrowed book"}), status=403) BorrowBook(user=user, book=book).save() book.quantity -= 1 book.save() return Response(json.dumps({ "Message": "Book borrowed successfully", "Book": book.serialize }), status=200) return Response(json.dumps({"Message": "Book does not exist"}), status=404) return Response(json.dumps({"Message": "User does not not exist"}), status=404)
def get(self): """Function serving get all books api endpoint""" q = request.args.get("q") if q: return Response(json.dumps(Book.search(q)), status=200) page = request.args.get("page") if page: page = int(page) else: page = 1 limit = request.args.get("limit") if limit: limit = int(limit) else: limit = 10 books = Book.query.paginate(page=page, per_page=limit, error_out=False) all_books = books.items if len(all_books) == 0: return Response(json.dumps({"Message": "No books found"}), status=404) total_pages = books.pages current_page = books.page return Response(json.dumps({ "Books": [book.serialize for book in all_books], "totalPages": total_pages, "currentPage": current_page }), status=200)
def post(self): """Method serving add book api endpoint""" current_user = get_jwt_identity() user = User.get_user_by_username(current_user) if user: if user.is_admin: data = request.get_json(self) if validate_book(data): return Response(json.dumps(validate_book(data)), status=400) if len(data['isbn']) not in (10, 13): return Response(json.dumps({"Message": "Invalid ISBN"}), status=403) isbn = Book.query.filter_by(isbn=data['isbn']).first() if isbn: return Response(json.dumps( {"Message": "Book already exists"}), status=409) Book(data['title'], data['author'], data['isbn'], data['publisher'], data['quantity']).save() book = Book.query.filter_by(isbn=data['isbn']).first() return Response(json.dumps({ "Message": "Book added successfully", "Book": book.serialize }), status=201) return Response(json.dumps({"Message": "User not an admin"}), status=401) return Response(json.dumps({"Message": "User does not exist"}), status=404)
def add_book(request): if request.method == 'POST': payload = json.loads(request.body) book = Book(name=payload['name'], value=payload['value']) try: book.save() result = json.dumps([{'message': 'success'}]) except: result = json.dumps([{'message': 'error'}]) return HttpResponse(result, content_type='text/json')
def post(self, request, id): book = Book(publishing_house=self.get_object(id)) serializer = BookSerializer(book, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors)
def book(request): if request.method == 'GET': book_list = Book.objects.all() # book_list= serializers.serialize("json", book_list) # book_list_json = [] for book in book_list: book_list_json.append(book.to_dict()) data = { 'status': 200, 'msg': 'ok', 'data': book_list_json, } return JsonResponse(data=data) elif request.method == 'POST': b_name = request.POST.get('b_name') b_price = request.POST.get('b_price') book = Book() book.b_name = b_name book.b_price = b_price book.save() data = { 'status': 201, 'msg': 'add success', 'data': book.to_dict(), } return JsonResponse(data=data)
def get(self, book_id): """Function serving get a book api endpoint""" if validate_arg(book_id): return validate_arg(book_id) book = Book.get_book_by_id(id=book_id) if not book: return Response(json.dumps({"Message": "Book does not exist"}), status=404) return Response(json.dumps(book.serialize), status=200)
def __handle_create_book_post(request): try: title = request.POST['title'] year_published = request.POST['year_published'] rating = request.POST['rating'] author_id = request.POST['author'] author = Author.objects.get(pk=author_id) book = Book( title=title, year_published=year_published, rating=rating, author=author, ) book.save() return generate_response("book saved", True, book) except KeyError as e: return generate_response("missing %s" % e.args[0].strip("'"), False) except Exception as e: return generate_response(str(e), False)
class ReviewModelTestCase(TestCase): def setUp(self): self.book = Book(author='J.R.R. Tolkien', title='The Hobbit') self.book.save() self.review = Review(book=self.book, review=5) def test_review_creation(self): self.review.save() self.assertIsNotNone(self.review.id) def test_review_low_validation(self): with self.assertRaises(ValidationError): self.review.review = -1 self.review.full_clean() def test_review_high_validation(self): with self.assertRaises(ValidationError): self.review.review = 6 self.review.full_clean()
def put(self, book_id): """ Function to update a book :param book_id: :return: """ data = request.get_json(self) book_find = Book.getBook(book_id) if not book_find: return {'Error': 'Book Does not Exist'}, 404 if len(data) == 0: response = jsonify({"Message": "No Book Update Infomation Passed"}) response.status_code = 400 return response valid_book = BookSchema().load(data) if not valid_book.data["title"]: return {'Error': 'Book must have a Title'}, 403 elif valid_book.data["title"].isspace(): return {'Error': 'Book must have a Title'}, 403 elif valid_book.data["description"].isspace(): return {'Error': 'Book must have a Description'}, 403 elif not valid_book.data["description"]: return {'Error': 'Book must have a Description'}, 403 elif not valid_book.data["author"]: return {'Error': 'Book must have an Author'}, 403 elif valid_book.data["author"].isspace(): return {'Error': 'Book must have a Author'}, 403 response = jsonify(Book.updateBook(book_id=book_id, data=data)) response.status_code = 200 return response
def post(self): title = request.json.get("title") publisher_id = request.json.get("publisher_id") author_list = request.json.get("author_list") aut_list = [] for i in author_list: aut_list.append(Author.query.filter(Author.id == i).first()) book = Book(title=title, publisher_id=publisher_id, authors=aut_list) db.session.add(book) db.session.commit() return {"code": 1000, "msg": "ok", "data": book_ser(book)}
def add_books(self): book_titles = [ 'The Death and Life of Great American Cities', 'Salt, Fat, Acid, Heat', 'The New Jim Crow' ] for title in book_titles: exists = db.session.query( Book.id).filter_by(title=title).scalar() is not None if not exists: print('Adding the book {} to DB.'.format(title)) new_book = Book(title=title) db.session.add(new_book)
def get_book(dir): """ Beta version. Persist the book data (except the pictures) with the manifest informations. :param dir: :return: """ data = get_book_structure(dir) book = Book(name=path.split(dir)[-1]) book.save() for chapter, _ in data: new_chapter = Chapter(name=chapter, book=book) new_chapter.save() book.chapters.add(new_chapter) for subchapter in getattr(data, chapter).sub_chapters.keys(): cur_chapter = getattr(data, chapter) cur_subchapter = getattr(cur_chapter.sub_chapters, subchapter) new_subchapter = SubChapter(name=cur_subchapter.name, chapter=new_chapter, rank=cur_subchapter.rank, content=cur_subchapter.content) new_subchapter.save() new_chapter.sub_chapters.add(new_subchapter) new_chapter.save() book.save()
def thread_scrape_category(self, category): c_name, c_url = category c = Category(name=c_name) c.save() while c_url: try: htmlparsed = get_html_parsed(c_url) except HTTPError: c_url = None # Skip rest of category on http error else: books_url = get_books_url(c_url, htmlparsed) c_url = get_next_page(c_url, htmlparsed) for b_url in books_url: try: book_detail = get_book_detail(b_url) except HTTPError: pass # Skip book on http error else: b = Book(category=c, **book_detail) b.save() self.stdout.write(f'Category {c_name} successfully scraped')
def get(self): """ Function to get all books :return: """ allbooks = [] data = Book.get_all_books() for book in data: allbooks.append(book.serialize()) response = jsonify(allbooks) response.status_code = 200 return response
class BookModelTestCase(TestCase): def setUp(self): self.book = Book(author='J.R.R. Tolkien', title='The Hobbit') def test_book_creation(self): self.book.full_clean() self.book.save() self.assertIsNotNone(self.book.id) def test_book_author_validation(self): with self.assertRaises(ValidationError): self.book.author = "Jakub Klawikowski" self.book.full_clean() def test_book_title_validation(self): with self.assertRaises(ValidationError): self.book.title = "Not a book tiitle" self.book.full_clean()
def create_book_helper(user_data): # check all fields are entered if invalid_book_data(user_data): return create_response( message="Missing name, author, grade, year, or published", status=400, data={"status": "failure"}, ) if user_data["grade"] not in valid_grades: return create_response( message="Grade is not valid, must be Middle or Intermediate", status=400, data={"status": "failure"}, ) # check book if not already in database dup_book = (Book.query.filter_by(name=user_data["name"]).filter_by( author=user_data["author"]).filter_by( grade=user_data["grade"]).filter_by( year=user_data["year"]).first()) if not (dup_book is None): return create_response(message="Book already exists", status=409, data={"status": "failure"}) # add book to database book = Book( user_data["name"], user_data["author"], user_data["grade"], user_data["year"], # if cover url exists then return it, otherwise use empty string user_data.get("cover_url", ""), user_data["published"], ) db.session.add(book) db.session.commit() return create_response(message="Book added", status=200, data={"status": "success"})
def books(request): if request.method == "POST": b_name = request.POST.get("b_name") b_price = request.POST.get("b_price") book = Book() book.b_name = b_name book.b_price = b_price book.save() data = { 'status': 201, 'message': "update success", 'data': book.book_to_dict() } return JsonResponse(data=data) if request.method == "GET": book_dict = [] book_list = Book.objects.all() for book in book_list: book_dict.append(book.book_to_dict()) data = {'status': 200, 'message': 'get success', 'data': book_dict} return JsonResponse(data=data)
def get(self, book_id): """ Function to find a single book :param book_id: :return: thisBook """ thisbook = [] data = Book.getBook(book_id) if not data: return {'Error': 'Book Does not Exist'}, 404 else: thisbook.append(data.serialize()) response = jsonify(thisbook) response.status_code = 200 return response
def books(request): if request.method == 'GET': books = Book.objects.filter().all() # booklist = books.values_list() # print(booklist) print(books) booklist = [book.to_dict() for book in books] data = {'status': 200, 'msg': 'ok', 'data': booklist} return JsonResponse(data=data) elif request.method == 'POST': # # print(request.POST.keys()) # book_name = request.GET.get('book_name') # book_price = request.GET.get('book_price') # request.GET.dict() book_name = request.POST.get('book_name') book_price = request.POST.get('book_price') print(book_name) print(book_price) # book = Book( **{'name' : book_name, 'price' : book_price} ) # book = Book(name=book_name, price = book_price) book = Book() book.name = book_name book.price = book_price book.save() rspdata = { 'status': 201, 'msg': 'create sucess', 'data': book.to_dict() } return JsonResponse(data=rspdata)
def post(self, request, filename, format='tr'): if request.method == 'POST' and request.data['upload']: # TODO: remove this functionality response = {} uuid_name = str(time.time()) + str(uuid.uuid4()) tempFolder = os.path.join( settings.BASE_DIR, "media/dump/" + uuid_name) if not os.path.exists(tempFolder): os.makedirs(tempFolder) data = request.data['upload'] with open(os.path.join(tempFolder, "source.tr"), 'w') as temp_file: for line in data: temp_file.write(line) try: FNULL = open(os.devnull, 'w') out = subprocess.check_output( ['java', '-jar', os.path.join( settings.BASE_DIR, 'aoh/aoh.jar'), '-x', tempFolder + "/source.tr"], stderr=subprocess.STDOUT ) os.remove(os.path.join(tempFolder, "source.tr")) FNULL.close() bookname = '' bookcode = '' langname = '' langcode = '' for root, dirs, files in os.walk(tempFolder): for f in files: abpath = os.path.join(root, os.path.basename(f)) relpath = FileUtility.relative_path(abpath) meta = TinyTag.get(abpath) if meta and meta.artist: a = meta.artist lastindex = a.rfind("}") + 1 substr = a[:lastindex] pls = json.loads(substr) if bookcode != pls['slug']: bookcode = pls['slug'] bookname = Book.getBookByCode(bookcode) if langcode != pls['language']: langcode = pls['language'] langname = Language.getLanguageByCode(langcode) data = { "langname": langname, "bookname": bookname, "duration": meta.duration } # highPassFilter(abpath) saved = Take.prepareDataToSave( pls, relpath, data, True) if "language" in saved and "language" not in response: response["language"] = saved["language"] if "book" in saved and "book" not in response: response["book"] = saved["book"] else: return Response({"error": "bad_wave_file"}, status=400) return Response(response, status=200) except Exception as e: shutil.rmtree(tempFolder) return Response({"error": str(e)}, status=400)