def book(request): if request.method == "GET": books = Book.objects.all() data = [] for book in books: data.append({'url': book.url, 'id': book.id}) response = HttpResponse(json.dumps(data), mimetype="application/json") return response elif request.method == "POST": #extract data and converts to object data = json.loads(request.POST.get('data')) #extract the file and the filename image = request.FILES['image'] filename = settings.MEDIA_ROOT + image.name #write the file to disk with open(filename, 'wb+') as destination: for chunk in image.chunks(): destination.write(chunk) book = Book() if "description" in data: book.description = data["description"] if "category" in data: book.category = data["category"] data = book.upload(filename) response = HttpResponse(json.dumps(data), mimetype="application/json") response.status_code = 201 return response
def upload(request): if request.user.is_staff is True: if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): newdoc = Book(pdf_file=request.FILES['pdf_file'], title=request.POST['title'], lowercase_title=request.POST['title'].lower(), image=request.FILES['image']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect('/upload/') else: form = UploadFileForm() # A empty, unbound form # Load documents for the list page documents = Book.objects.all() # Render list page with the documents and the form return render(request, 'library/upload.html', { 'documents': documents, 'form': form }) else: redirect('/')
def create(self, validated_data): # Check if category exists category = Category.objects.filter( name=validated_data['category']['name']) if category.count() <= 0: error = {'message': 'There is no such category'} raise serializers.ValidationError(error) # Check if author exists for author in validated_data['authors']: authors = Author.objects.filter(name=author['name']) if authors.count() <= 0: error = {'message': 'There is no such author'} raise serializers.ValidationError(error) title = validated_data['title'] isbn = validated_data['isbn'] pub_date = validated_data['pub_date'] book = Book(title=title, isbn=isbn, pub_date=pub_date, category=category[0]) book.save() # After creating model instance add authors for author in validated_data['authors']: author_obj = Author.objects.filter(name=author['name'])[0] book.authors.add(author_obj) return book
def insertbook(request): is_book = False if request.method == "POST": isbn = request.POST["ISBN"] title = request.POST["Title"] authorid = request.POST["AuthorID"] publisher = request.POST["Publisher"] publishdate = request.POST["PublishDate"] price = request.POST["Price"] try: Book.objects.get(ISBN = isbn) except: try: Author.objects.get(AuthorID = authorid) except: return render_to_response("insertauthor.html",{'isbn':isbn,"title":title, "publisher":publisher,"price":price, "authorID":authorid,"publishdate":publishdate}) else: newbook = Book(ISBN = isbn, Title = title, AuthorID = Author.objects.get(AuthorID = authorid), Publisher = publisher, PublishDate = publishdate, Price = price) newbook.save() return HttpResponseRedirect("/booklist/") else: is_book = True return render_to_response("insertbook.html",{"is_book":is_book})
def aabook(request): if request.method == 'POST': title = request.POST['title'] author = request.POST['author'] year = request.POST['year'] publisher = request.POST['publisher'] desc = request.POST['desc'] cover = request.FILES['cover'] pdf = request.FILES['pdf'] current_user = request.user user_id = current_user.id username = current_user.username a = Book(title=title, author=author, year=year, publisher=publisher, desc=desc, cover=cover, pdf=pdf, uploaded_by=username, user_id=user_id) a.save() messages.success(request, 'Book was uploaded successfully') return redirect('albook') else: messages.error(request, 'Book was not uploaded successfully') return redirect('aabook_form')
def search_googlex(request): """ Searches google books for a book with the given barcode (isbn) """ if request.method == 'POST': form = BookSearch(request.POST) barcode = form.data['barcode'] response = google_books.search(barcode) print "I passed the loop" if request.is_ajax(): print "I think I am ajax" json = simplejson.dumps(response) return HttpResponse(json, mimetype='application/json') return render(request, 'search.html', {'book_list': response['book_list'], 'form': form, 'title' :'Search Google'}) else: book = Book(author='a', title='t') book.id = 'dummy' form = BookSearch() return render(request, 'search.html', {'form': form, 'title' : 'Search Google', 'book_list' : [book]},)
def bookCreate(request): if request.method == "POST": body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) fields = ['code', 'title', 'author', 'date_launch', 'amount_available'] for field in fields: try: body[field] except: return JsonResponse( {"erro": 'campo ' + field + ' nao fornecido'}, safe=False) if verifyCode(body['code']): return JsonResponse( {"error": "código do livro já está cadastrado"}) book = Book(code=body['code'], title=body['title'], author=body['author'], date_launch=body['date_launch'], date_register=body['date_register'] if 'date_register' in body else timezone.now(), amount_available=body['amount_available']) book.save() return JsonResponse({})
def search_googlex(request): """ Searches google books for a book with the given barcode (isbn) """ if request.method == 'POST': form = BookSearch(request.POST) barcode = form.data['barcode'] response = google_books.search(barcode) print "I passed the loop" if request.is_ajax(): print "I think I am ajax" json = simplejson.dumps(response) return HttpResponse(json, mimetype='application/json') return render( request, 'search.html', { 'book_list': response['book_list'], 'form': form, 'title': 'Search Google' }) else: book = Book(author='a', title='t') book.id = 'dummy' form = BookSearch() return render( request, 'search.html', { 'form': form, 'title': 'Search Google', 'book_list': [book] }, )
def book(request): if request.method == "GET": books = Book.objects.all() data=[] for book in books: data.append({'url':book.url, 'id':book.id}) response = HttpResponse(json.dumps(data), mimetype="application/json") return response elif request.method == "POST": #extract data and converts to object data = json.loads(request.POST.get('data')) #extract the file and the filename image = request.FILES['image'] filename = settings.MEDIA_ROOT+image.name #write the file to disk with open(filename, 'wb+' ) as destination: for chunk in image.chunks(): destination.write(chunk) book = Book() if "description" in data: book.description = data["description"] if "category" in data: book.category = data["category"] data = book.upload(filename) response = HttpResponse(json.dumps(data), mimetype="application/json") response.status_code = 201 return response
def test_ownership_new_other_ownership_someone_else(self): """Test the algorithm determining if a new ownership is necessary""" book = Book(title="Some annoying book") book.save() ownership = Ownership(book=book,owner=self.bib) existing_ownership = Ownership(book=book,owner=self.bob) self.assertTrue(determine_new_ownership_necessary(ownership,existing_ownership))
def test_add_book_new_other_ownership(self): """Test the view adding a book to a library""" book = Book(title="Some really annoying book") book.save() existing_ownership = Ownership(owner=self.bib,book=book,copies=10) existing_ownership.save() data = { 'copies':42, } response = self.client.post(reverse('book_add_this_to_my_library',kwargs={'book_id':book.id}),data) self.assertEqual(response.status_code, 302) try: ownership = Ownership.objects.get(owner__id=self.bib.id,book__id=book.id) except Ownership.DoesNotExist: ownership = None self.assertIsNotNone(ownership) self.assertEqual(ownership.id,existing_ownership.id) self.assertRedirects(response, reverse('book_detail',args=[book.id])) response = self.client.get(reverse('book_detail',args=[book.id])) self.assertContains(response, self.bib.username.title() + " (" + str(existing_ownership.copies+data['copies']) + ")") self.client.logout()
def add_book(request): if request.method == 'GET': return render_to_response('add_book.html') else: isempty = False if request.POST: post = request.POST post_attr_list = ['title', 'category', 'press', 'year', 'author', 'price', 'total', 'stock'] old_book = Book.objects.filter(title=post['title']).first() for post_attr in post_attr_list: if post[post_attr] == '': isempty = True continue if isempty is False and old_book is None: new_book = Book( title=post['title'], category=post['category'], press=post['press'], year=post['year'], author=post['author'], price=post['price'], total=post['total'], stock=post['stock'], ) new_book.save() add_msg = '添加成功!' return render(request, 'add_book.html', {'success_msg': add_msg}) elif old_book is not None: add_msg = '该书已存在!' return render(request, 'add_book.html', {'fail_msg': add_msg}) else: add_msg = '请输入图书信息!' return render(request, 'add_book.html', {'enter_none': add_msg})
def handle(self, *args, **options): with open('./library/management/commands/words.txt', 'r') as file: words = file.read() words = words.split('\n') for i in range(40): random_word = random.choice(words) print(f"Searching for book: {random_word}.") response = requests.get('http://openlibrary.org/search.json?q=' + random_word) data = json.loads(response.text) if len(data['docs']) == 0: continue book_data = random.choice(data['docs']) title = book_data['title'] if 'first_publish_year' not in book_data: continue year_published = book_data['first_publish_year'] authors = book_data.get('author_name', ['No Author']) #get or create for this. if Book.objects.filter(title=title, year_published=year_published).exists(): continue book = Book(title=title, year_published=year_published) book.save() for author in authors: author, created = Author.objects.get_or_create(name=author) book.authors.add(author) print(str(round(i / 40 * 100, 2)) + '%')
def add(request): if request.POST and request.POST['Name'] and request.POST['Title'] and request.POST['ISBN_PK'] and request.POST['AuthorID_FK']: post = request.POST new_author=Author( AuthorID_FK = post['AuthorID_FK'], Name = post['Name'], Age = post['Age'], Country = post['Country'], ) tmp = list(Author.objects.filter(Name=post['Name'])) tmp0 = list(Author.objects.filter(AuthorID_FK=post['AuthorID_FK'])) if tmp0 != []: return render_to_response("addauerror.html") else: if tmp == [] : new_author.save() else: new_author=Author.objects.filter(Name=post['Name'])[0] new_book = Book( ISBN_PK = post["ISBN_PK"], Title = post["Title"], AuthorID_FK = new_author, Publisher = post["Publisher"], PublishDate = post["PublishDate"], Price = post["Price"], ) tmp1 = list(Book.objects.filter(ISBN_PK=post['ISBN_PK'])) if tmp1!=[]: return render_to_response("addboerror.html") else: new_book.save() return render_to_response("addbosuccess.html") else: return render_to_response("addboerror1.html")
def test_book_no_owners(self): book = Book(title="The Bloubiboulga's guide to bloblob Tests") book.save() response = self.client.get(reverse('book_remove_from_library',kwargs={'book_id':book.id})) self.assertEqual(response.status_code, 404) self.client.logout()
def append(request): if request.POST: post = request.POST book = Book( ISBN= post["ISBN"],Title = post["Title"] ,Publisher=post["Publisher"], AuthorID=post["AuthorID"],Price=post["Price"],PublishDate=post["PublishDate"]) book.save() authorid = post["AuthorID"] try: author = Author.objects.filter(AuthorID =authorid)[0] return render_to_response("success.html") except: return render_to_response("appendauthor.html")
def test_book_remove_from_my_library_not_mine(self): book = Book(title="The Hitchhikers guide to Django Unit Tests without special caracter") book.save() book.owners.clear() ownership = Ownership(book=book,owner=self.bob) ownership.save() response = self.client.get(reverse('book_remove_from_library',kwargs={'book_id':book.id})) self.assertEqual(response.status_code, 302) self.assertRedirects(response, reverse('book_list')) self.client.logout()
def setUp(self): self.author = Author(name='John Doe') self.author.save() self.category = Category(description='Comedy', ) self.category.save() self.book = Book(title='Any book', author=self.author, category=self.category, pages=900, description='', published_in=datetime.today()) self.book.save()
def books(request): if request.method == "POST": title = request.POST['title'] author = request.POST['author'] cat = Category.objects.get(id=int(request.POST['category_id'])) description = request.POST['description'] available = int(request.POST['quantity']) book = Book(title=title, author=author, description=description, available=available) book.save() if book.categories.add(cat): return redirect('/books') books = Book.objects.all() categories = Category.objects.all() return render(request, "books.html", {"books": books, "categories": categories})
def test_book_remove_from_my_library(self): book = Book(title="The Hitchhikers guide to bloblob Tests without special caracter") book.save() ownership = Ownership(book=book,owner=self.bob) ownership.save() ownership = Ownership(book=book,owner=self.bib) ownership.save() response = self.client.get(reverse('book_remove_from_library',kwargs={'book_id':book.id})) self.assertEqual(response.status_code, 200) self.assertContains(response, "Êtes-vous certain que vous souhaitez supprimer \"%(object)s\" ?" % {'object':book.title}) self.client.logout()
def setUpTestData(cls): Book.objects.bulk_create([ Book(title='Test Book', author='John Doe', pub_date=1999, isbn=1234567890123, pages=30, lang='en'), Book(title='Książka', author='Adam Kowal', pub_date=1968, isbn=3210987654321, pages=45, lang='pl') ])
def handle(self, *args, **options): with open('library/management/commands/booklist.json', 'r') as books_json: text = books_json.read() books = json.loads(text) for book in books['books']: author = book['author'] title = book['title'] image = book['image'] year = book['year'] pages = book['pages'] url = book['url'] country = book['country'] language = book['language'] output_book = Book(author=author, title=title, image=image, year=year, pages=pages, url=url, country=country, language=language) output_book.save()
def test_assertBook_from_dict_AuthorsNoSortkey(self): book = { 'title': 'Test 4', 'authors': ('Author 4a', 'Author 4b'), } newbook = Book.from_dict(book) self.assertEqual(diff_books(self.testbook4, newbook), {})
def accept_suggested_book(request, pk): """View function for accepting a SuggestedBook and creating a Book.""" suggested_book = get_object_or_404(SuggestedBook, pk=pk) # if the request is a GET (the user requests the /suggestions/<book>/accept url) # create a Book from the SuggestedBook object and remove SuggestedBook if request.method == 'GET': # check to see if author already exists author = Author.objects.filter(name=suggested_book.author).first() if not author: author = Author(name = suggested_book.author) author.save() Book( title = suggested_book.title, author = author, url = suggested_book.url, description = suggested_book.description ).save() suggested_book.delete() messages.success(request, 'You accepted the suggested book.') # redirect to a new URL: return HttpResponseRedirect(request.GET.get("next"))
class BookTestCase(TestCase): def setUp(self): self.testbook1 = Book(title='Test 1', sortkey='Author 1', year_published=date(2013,1,1)) def test_Book_display_authors(self): self.assertEqual(self.testbook1.sortkey, self.testbook1.display_authors())
def load(): f = open('diskBooksData.txt', 'r') f.readline() for line in f: fields = line.rstrip().split('\t') b = Book( filename=fields[0], title=fields[1], author=fields[2], language=fields[3], happs=0.0, length=0, ignorewords='', wiki='http://example.com', ) b.save()
def test_assertBook_from_dict_EqualNoYear(self): book = { 'title': 'Test 2', 'sortkey': 'Author 2', } newbook = Book.from_dict(book) self.assertEqual(diff_books(self.testbook2, newbook), {})
def handle(self, *args, **options): chunk_size = options.get("chunk") bulk_mngr = BulkCreateManager(chunk_size) fake = Faker() for counter in range(self.NO_OF_SEED_LIBRARY): library = Library(name=fake.name() + " Library", updated_at=timezone.now(), archived=False) bulk_mngr.add(library) bulk_mngr.done() library_qs = Library.objects.all() print("-- Done creating libraries --") for library in library_qs: no_of_books_for_library = random.randint( self.MIN_NO_OF_BOOKS_PER_LIBRARY, self.MAX_NO_OF_BOOKS_PER_LIBRARY) print("-- Adding %s books to %s(%s) --" % (no_of_books_for_library, library.name, library.id)) for counter in range(no_of_books_for_library): book = Book(title=fake.sentence(), publisher=fake.company(), library=library, updated_at=timezone.now(), archived=False) bulk_mngr.add(book) bulk_mngr.done()
def add_book(request): if request.POST: post = request.POST try: author = Author.objects.get(Name = post["AuthorName"]) new_book = Book( ISBN = post["ISBN"], Title = post["Title"], AuthorID = author, Publisher = post["Publisher"], PublishDate = post["PublishDate"], Price = post["Price"]) new_book.save() except: right="create author first" return render_to_response("add_book.html",Context({"count":Book.objects.filter().count(),"right":right})) return render_to_response("add_book.html",Context({"count":Book.objects.filter().count()}))
def insertauthor(request): if request.method == "POST": authorID = request.POST["AuthorID"] newauthor = Author(AuthorID = request.POST["AuthorID"], Name = request.POST["Name"], Age = request.POST["Age"], Country = request.POST["Country"]) newauthor.save() newbook = Book(ISBN = request.POST["ISBN"], Title = request.POST["Title"], AuthorID = Author.objects.get(AuthorID = authorID), Publisher = request.POST["Publisher"], PublishDate = request.POST["PublishDate"], Price = request.POST["Price"]) newbook.save() return HttpResponseRedirect("/booklist/") return render_to_response("insertauthor.html")
def test_assertBook_from_dict_AuthorsAndSortkey(self): book = { 'title': 'Test 3', 'sortkey': 'Author 3a, Author 3b', 'authors': ('Author 3a', 'Author 3b'), } newbook = Book.from_dict(book) self.assertEqual(diff_books(self.testbook3, newbook), {})
def test_assertBook_from_dict_EqualYear(self): book = { 'title': 'Test 1', 'sortkey': 'Author 1', 'year': 2013, } newbook = Book.from_dict(book) self.assertEqual(diff_books(self.testbook1, newbook), {})
def new_book(): if request.method == 'POST': book = Book(title=request.form['name'], author=request.form['author'], genre=request.form['genre']) session.add(book) session.commit() return redirect(url_for('show_books')) else: return render_template('newBook.html')
def handle(self, *args, **options): books_csv_paths = options[BOOKS] for csv_file_path in books_csv_paths: with open(csv_file_path, mode='r', encoding='UTF-8', newline='') as csv_file: csv_reader = csv.reader(csv_file, delimiter=';') next(csv_reader, None) for row in csv_reader: new_book = Book(isnb=row[0], title=row[1], author=row[2], genre=row[3]) try: new_book.save() except ValueError as v_err: self.stdout.write( self.style.ERROR(f'Book{row[1]} can not be saved')) self.stdout.write(self.style.SUCCESS('Books successfully loaded'))
async def test_query_book(mocker): class AsyncMock(MagicMock): async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) book_id = '1' double = mocker.patch.object(PostgresPersistence, 'filter', new_callable=AsyncMock) author = Author(name='martin fowler') category = Category(title='software engineering') book = Book(id=1, external_id=book_id, title='refactoring', subtitle='improving the design of existing code', authors=[author], categories=[category], published_year=1999, editor=Editor(name='addison wesley'), description='whatever', saved=True) double.return_value = [book] book_DTO = BookDTO( external_id=book_id, title='refactoring', subtitle='improving the design of existing code', authors=[{ 'name': 'martin fowler' }], categories=[{ 'title': 'software engineering' }], published_year=1999, editor={'name': 'addison wesley'}, description='whatever', ) insert_controller = InsertBookController(data=book_DTO) await insert_controller.insert() controller = QueryBookController() books = await controller.filter(external_id=book_id) book = books[0] double.assert_called_once_with(external_id=book_id) assert book.id assert book.external_id == book_id assert book.title == 'refactoring' assert book.subtitle == 'improving the design of existing code' assert book.authors[0].name == 'martin fowler' assert book.categories[0].title == 'software engineering' assert book.published_year == 1999 assert book.editor.name == 'addison wesley' assert book.description == 'whatever' assert book.saved is True
async def post(self, request): # populate the book with the data in the request book = Book(**request.json) # and await on save await book.save() return json({'method': request.method, 'status': 201, 'results': BookSerializer.serialize(book), })
def book_edit(request, book_id=None): """書籍の編集""" if book_id: # book_id が指定されている (修正時) book = get_object_or_404(Book, pk=book_id) else: # book_id が指定されていない (追加時) book = Book() if request.method == 'POST': form = BookForm(request.POST, instance=book) # POST された request データからフォームを作成 if form.is_valid(): # フォームのバリデーション if get_book_info(book): book = form.save(commit=False) book.save() return redirect('library:book_list') else: # GET の時 form = BookForm(instance=book) # book インスタンスからフォームを作成 return render(request, 'library/book_edit.html', dict(form=form, book_id=book_id))
async def post(self, request): # populate the book with the data in the request book = Book(**request.json) # and await on save await book.save() return json({ "method": request.method, "status": 201, "results": BookSerializer.serialize(book) })
def api_book_create(request): try: author = Author.objects.get(pk=11) bkc = Book(author=author) if request.method == "POST": bk_srl = BookSerializer(bkc, data=request.data) if bk_srl.is_valid(): bk_srl.save() return Response(bk_srl.data, status=status.HTTP_201_CREATED) return Response(bk_srl.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as e: print(e)
def test_add_book_no_ownership(self): """Test the view adding a book to a library""" book = Book(title="Some really annoying book") book.save() data = { 'copies':10, } response = self.client.post(reverse('book_add_this_to_my_library',kwargs={'book_id':book.id}),data) self.assertEqual(response.status_code, 302) try: ownership = Ownership.objects.get(owner__id=self.bib.id,book__id=book.id) except Ownership.DoesNotExist: ownership = None self.assertIsNotNone(ownership) self.assertRedirects(response, reverse('book_detail',args=[book.id])) self.client.logout()
def init_book(self): # Define a boundary on random dates. start_date = date(1983, 1, 1).toordinal() end_date = date.today().toordinal() authors = Author.objects.all() # Now generate the data for books. for publisher in Publisher.objects.all(): # Each publisher will get 2 books. for book_index in range(1, 3): title = self.rand_join(" ", ["Rearing", "Cooking", "Observing", "Identifying", "Petting"], ["Birds", "Dogs", "Cats", "Snails", "Lizards"]) isbn = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(0, 13)) publication_date = date.fromordinal(random.randint(start_date, end_date)) book = Book(title=title, isbn=isbn, publisher=publisher, publication_date=publication_date) book.save() # Now associate the book with a number of authors. for x in range(0, random.randint(1, 3)): author = authors[random.randint(0, len(authors)-1)] book.authors.add(author)
def handle(self, *args, **options): Book.objects.all().delete() with open(get_path('books.json'), 'r') as file: reader = json.load(file) i = 0 for book in reader: book = Book(title=reader[i]['title'], author=reader[i]['author'], description=reader[i]['description'], url=reader[i]['url'], slug=slugify(reader[i]['title'])) if 'image' in reader[i]: book.image.save( reader[i]['image'], File(open(get_path(reader[i]['image']), 'rb'))) book.save() print(f"Imported {reader[i]['title']}") i += 1
def loadBooks(): datareader = csv.reader(open('book.csv'), delimiter=',', quotechar='"') for row in tqdm(datareader): if row[0] != 'ISBN10': book = Book() book.isbn = row[0] book.title = row[1] book.save()
def post(self, request, *args, **kwargs): if request.content_type == 'text/plain;charset=UTF-8': data = json.loads(request.body.decode('utf-8')) else: data = request.data user = get_user_from_request(request) # todo: validation throuth forms title = data['title'] authors = data['authors'] genre = data['genre'] existing_books = Book.objects.filter(title__contains=title, authors__contains=authors) if existing_books: book = existing_books[0] else: book = Book(title=title, authors=authors, genre=genre) book.save() book_item = BookItem.objects.create(book=book, owner=user) if data.get('image'): path = 'books/{}/{}.jpg'.format(user.id, book_item.id) if data.get('image').find('data:image') != -1: image = data['image'] upload_file(path, image) book_item.image = MEDIA_URL + path if not book.image: book.image = MEDIA_URL + path book.save() book_item.save() else: book_item.image = data['image'] if not book.image: book.image = MEDIA_URL + path book.save() book_item.save() if data.get('isbn'): book_item.isbn = data['isbn'] book_item.save() serializer = self.get_serializer(book_item) return Response(serializer.data)
def AddBook2(request): AUTHOR = Author() AUTHOR.AulthorID = request.POST['author_ID'] AUTHOR.Age = request.POST['author_age'] AUTHOR.Country = request.POST['author_country'] AUTHOR.Name = request.POST['author_name'] AUTHOR.save() BOOK = Book() BOOK.Title = request.POST['book_name'] BOOK.AulthorID_id = request.POST['author_ID'] BOOK.Publisher = request.POST['book_publisher'] BOOK.PublishDate = request.POST['book_date'] BOOK.Price = float(request.POST['book_price']) BOOK.save() BookList = Book.objects.all() return render_to_response('BookList.html',{'BookList':BookList})
def handle(self, *args, **options): BookCheckout.objects.all().delete() Book.objects.all().delete() with open( r"C:\Users\Brandon\code\class_raccoon\Code\Brandon\Django\labs\library\management\commands\books.json", "r") as f: books = json.loads(f.read()) for book in books: author = book['author'] if not Author.objects.filter(author=author).exists(): author = Author(author=author) author.save() else: author = Author.objects.get(author=author) title = book['title'] year_published = book['year'] url = book['link'] book = Book(title=title, year_published=year_published, author=author, url=url) book.save()
def handle_suggestion(request): if request.method == "POST": confirmation = request.POST['confirmation'] suggestion = Suggestion.objects.get(slug=request.POST['book-slug']) if confirmation == "confirm": book = Book(title=suggestion.title, author=suggestion.author, description=suggestion.description, url=suggestion.url, slug=slugify(suggestion.title)) if suggestion.image: book.image = suggestion.image suggestion.delete() book.save() return HttpResponse(json.dumps(["success"])) elif confirmation == "decline": suggestion.delete() return HttpResponse(json.dumps(["success"])) else: return Http404()
class BookTest(TestCase): def setUp(self): self.author = Author(name='John Doe') self.author.save() self.category = Category(description='Comedy', ) self.category.save() self.book = Book(title='Any book', author=self.author, category=self.category, pages=900, description='', published_in=datetime.today()) self.book.save() def test_create(self): 'Book instance may be saved' self.assertEqual(1, self.book.pk) def test_str(self): 'Book string representation may be the name.' self.assertEqual('Any book', str(self.book))
def test_query_book(loop): def book_api(request): pass routes = [Route('/book', book_api)] app = Starlette(routes=routes, debug=True) client = TestClient(app) book_id = 1 book = Book(id=book_id, title='refactoring', subtitle='improving the design of existing code', author=[Author(name='martin fowler')], category=[Category(title='software engineering')], published_year=1999, editor='addison wesley', description='whatever', saved=True) loop.run_until_complete(book.save()) query_response = client.get('/books', params={'title': 'refactoring'}) result = query_response.json()[0] assert result == [{ 'id': book_id, 'title': 'refactoring', 'subtitle': 'improving the design of existing code', 'author': [{ 'name': 'martin fowler' }], 'category': [{ 'title': 'software engineering' }], 'published_year': 1999, 'editor': 'addison wesley', 'description': 'whatever', 'saved': True }]
def addbook(request): title = request.POST['book_name'] #ISBN = request.POST['book_ISBN'] authorID = request.POST['book_authorID'] publisher = request.POST['book_publisher'] publishdate = request.POST['book_date'] price = request.POST['book_price'] try: author = Author.objects.get(AuthorID=authorID) BOOK = Book() BOOK.ISBN = request.POST['book_ISBN'] BOOK.Title = title BOOK.AuthorID = author BOOK.Publisher = publisher BOOK.Publishdate = publishdate BOOK.Price = float(price) BOOK.save() return render_to_response('bookinformation.html',{'booktest':BOOK}) except Author.DoesNotExist: return render_to_response('addwriter.html')
def handle(self, *args, **options): BooksCheckedOut.objects.all().delete() Book.objects.all().delete() with open("/Users/salamandersmith/Desktop/class_raccoon/Code/Alex/django/mysite/library/management/commands/books.json", "r") as f: books = json.loads(f.read()) for book in books: author = book['author'] if not Author.objects.filter(name=author).exists(): author = Author(name=author) author.save() else: author = Author.objects.get(name=author) #print(f"Author: {author.name}") title = book['title'] #print(f"Title: {title}") year_published = book['year'] #print(f"Year: {year_published}") pages = book['pages'] link = book['link'] country = book['country'] language = book['language'] book = Book(title=title, year_published=year_published, pages=pages, link=link, country=country, language=language) book.save() book.authors.add(author)
def save(self, file_csv): records = csv.reader(file_csv) next(records) # skip the first line for line in records: if len(line) == 7: title = line[0] author_lf = line[2] isbn = line[4] or None isbn13 = line[5] or None yr_published = line[6] or None author = Author.create_from_csv(author_lf) book = Book(title=title, isbn=isbn, isbn13=isbn13, year_published=yr_published) book.save() book.authors = author book.save()
def AddBook(request): name = request.POST['book_name'] #ISBN = request.POST['book_ISBN'] authorID = request.POST['book_authorID'] publisher = request.POST['book_publisher'] date = request.POST['book_date'] price = request.POST['book_price'] try: author = Author.objects.get(AulthorID=authorID) except Author.DoesNotExist: return render_to_response('AddBook2.html',{'AulthorID':authorID,'book_name':name,'book_publisher':publisher,'book_date':date,'book_price':price}) else: BOOK = Book() #BOOK.ISBN = ISBN BOOK.Title = name BOOK.AulthorID_id = authorID BOOK.Publisher = publisher BOOK.PublishDate = date BOOK.Price = float(price) BOOK.save() lis = Author.objects.all() lis2 = Book.objects.all() return render_to_response('index.html',{'AuthorList':lis,'BookList':lis2})
def search(request): """Search for books. GET: q -- the query string lucky -- whether the lucky button is clicked Renders library/searchResult.html with: q -- the query string result -- search result, as a list of books """ q = request.GET.get('q', '') lucky = 'lucky' in request.GET if lucky: try: book = choice(Book.objects.all()) return redirect('library:book', book.id) except IndexError as err: pass return render(request, 'library/searchResult.html', { 'q': q, 'result': Book.search(q), })
def test_ownership_new_no_ownership(self): """Test the algorithm determining if a new ownership is necessary""" book = Book(title="Some annoying book") book.save() ownership = Ownership(book=book,owner=self.bib) self.assertTrue(determine_new_ownership_necessary(ownership,None))
def setUp(self): self.testbook1 = Book(title='Test 1', sortkey='Author 1', year_published=date(2013,1,1))
def handle(self, filepath='', *args, **options): print filepath temp = filepath.split('/') lng = temp[0] collection = temp[1] pth = src / lng / collection if lng == 'otr': jsonpath = pth / 'meta' else: jsonpath = pth / 'books.json' jsonfile = open(jsonpath) txt=jsonfile.read() jsonfile.close() data_list = eval(txt) log = open('log','w') print 'items',len(data_list) for d in data_list: if lng == 'otr': bookset = Book.objects.filter(book_file=d['file']) else: bookset = Book.objects.filter(book_file=d['book_file']) #there should be at most one - delete all but one if bookset: for i in range(len(bookset)-1): bookset[i].delete() book = bookset[len(bookset)-1] #now update bookkeys = d.keys() for bookkey in bookkeys: if lng == 'otr': book.a_summary = d['description'] book.cover_img = d['img'] book.a_author = d['author'] book.a_title = d['title'] book.mime_type = d['mime'] book.book_file = d['file'] book.a_collection = collection book.dc_language = lng else: book.bookkey = d[bookkey] if bookkey == 'cover_img': book.cover_img = d['cover_img'] else: if lng == 'otr': book = Book() book.a_summary = d['description'] book.cover_img = d['img'] book.a_author = d['author'] book.a_title = d['title'] book.mime_type = d['mime'] book.book_file = d['file'] book.a_collection = collection book.dc_language = lng else: book = Book(**d) book.save() log.close()
def handle_noargs(self, **options): books = [] book = Book() book.uuid = "aaa" book.title = "Learning Web Design: A Beginner's Guide to HTML, CSS, JavaScript, and Web Graphics" book.author_lastname = "Robbins" book.author_firstname = "Jennifer" book.description = """ Do you want to build web pages, but have no previous experience? This friendly guide is the perfect place to start. You'll begin at square one, learning how the Web and web pages work, and then steadily build from there. By the end of the book, you'll have the skills to create a simple site with multi-column pages that adapt for mobile devices. Learn how to use the latest techniques, best practices, and current web standards--including HTML5 and CSS3. Each chapter provides exercises to help you to learn various techniques, and short quizzes to make sure you understand key concepts. This thoroughly revised edition is ideal for students and professionals of all backgrounds and skill levels, whether you're a beginner or brushing up on existing skills. """ book.isbn10 = "1449319270" book.publisher = "O'reilly" books.append(book) book = Book() book.uuid = "aab" book.title = "HTML and CSS: Design and Build Websites" book.author_lastname = "Duckett" book.author_firstname = "Jon" book.description = """ Every day, more and more people want to learn some HTML and CSS. Joining the professional web designers and programmers are new audiences who need to know a little bit of code at work (update a content management system or e-commerce store) and those who want to make their personal blogs more attractive. Many books teaching HTML and CSS are dry and only written for those who want to become programmers, which is why this book takes an entirely new approach. Introduces HTML and CSS in a way that makes them accessible to everyone--hobbyists, students, and professionals--and it's full-color throughout Utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging Boasts a unique structure that allows you to progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure """ book.isbn10 = "1118008189" book.publisher = "Wiley" books.append(book) book = Book() book.uuid = "aac" book.title = "JavaScript & jQuery: The Missing Manual" book.author_lastname = "McFarland" book.author_firstname = "David" book.description = """ JavaScript lets you supercharge your HTML with animation, interactivity, and visual effects--but many web designers find the language hard to learn. This jargon-free guide covers JavaScript basics and shows you how to save time and effort with the jQuery library of prewritten JavaScript code. You'll soon be building web pages that feel and act like desktop programs, without having to do much programming. """ book.isbn10 = "1449399029" book.publisher = "O'reilly" books.append(book) # add all the books that don't exist yet for book in books: try: Book.objects.get(uuid=book.uuid) except Book.DoesNotExist: book.save()