def setUp(self): self.book = Book(isbn='0-306-40615-2', title='title', price=10, author='author', image='test.jpg') self.book.save() self.book2 = Book(isbn='85-359-0277-5', title='title2', price=10, author='author2', image='test.jpg') self.book2.save()
def test_book2(): """ Tests Book model, creation and the correct storage of the information. This time only with mandatory information """ isbn = str(random.randint(0, 5156123423456015412))[:12] user = User.objects.all().last() title = 'THis is the TITLE' price = 23.45 language = 'Espanol' primary_genre = 'FANT' publisher = 'Alejandria' num_pages = 100 obj = Book(ISBN=isbn, user_id=user, title=title, price=price, language=language, primary_genre=primary_genre, publisher=publisher, num_pages=num_pages) obj.save() obj = Book.objects.all().filter(pk=isbn).first() check = all([ isbn == obj.ISBN, user == obj.user_id, title == obj.title, price == float(obj.price), language == obj.language, primary_genre == obj.primary_genre, publisher == obj.publisher, num_pages == obj.num_pages ]) assert check
def _handle_csv(self, csvpath): """ Store books from a file in CSV format. WARN: does not handle tags """ csvfile = open(csvpath) dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) # TODO: Figure out if this is a valid CSV file status_published = Status.objects.get(status='Published') for row in reader: path = row[0] title = row[1] author = row[2] summary = row[3] if os.path.exists(path): f = open(path) book = Book(book_file=File(f), a_title=title, a_author=author, a_summary=summary, a_status=status_published) try: book.save() except: print "EXCEPTION SAVING FILE '%s': %s" % ( path, sys.exc_info()[0]) else: print "FILE NOT FOUND '%s'" % path
def create_book(genre): """ Tests Book model, creation and the correct storage of the information""" isbn = str(random.randint(0, 5156123423456015412))[:12] user = create_user() title = 'THis is the TITLE' description = 'This is the description of a test book' saga = 'SAGA\'S NAME' author = "Author" price = 23.45 language = 'Espanol' primary_genre = genre publisher = 'Alejandria' num_pages = 100 num_sold = 0 recommended_age = 'Juvenile' obj = Book(ISBN=isbn, user_id=user, title=title, description=description, saga=saga, price=price, language=language, primary_genre=primary_genre, publisher=publisher, num_pages=num_pages, num_sold=num_sold, recommended_age=recommended_age) obj.save() return obj
def setUp(self): self.author_one = AuthorFactory(name="Author 1") self.author_two = AuthorFactory(name="Author 2") self.book = Book(title="My Book") self.book.save() self.book.authors.add(self.author_one.pk, self.author_two.pk)
def process_books_summary(self, session, user, book_list): seller_book_list = [] amounts = {} for book in book_list: amount = book['amount'] del book['amount'] dbbook = Book(owner=user, accepted=False, sold=False) if 'pk' in book: dbbook.book_type_id = book['pk'] seller_book_list.append(book['pk']) amounts[book['pk']] = amount else: book['isbn'] = re.sub(r'[^\dX]+', '', book['isbn'].upper()) book['price'] = Decimal(book['price']) if book['publication_year'] == "": book['publication_year'] = 1970 book_type = BookType(**book) book_type.save() dbbook.book_type = book_type seller_book_list.append(book_type.pk) amounts[book_type.pk] = amount dbbook_list = [] for i in range(0, amount): dbbook.pk = None dbbook_list.append(dbbook) Book.objects.bulk_create(dbbook_list) session['seller_books'] = (seller_book_list, amounts) return True, None
def _handle_json(self, jsonpath): """ Store books from a file in JSON format. """ jsonfile = open(jsonpath) data_list = json.loads(jsonfile.read()) for d in data_list: # Get a Django File from the given path: f = open(d['book_path']) d['book_file'] = File(f) del d['book_path'] if d.has_key('cover_path'): f_cover = open(d['cover_path']) d['cover_img'] = File(f_cover) del d['cover_path'] if d.has_key('a_status'): d['a_status'] = Status.objects.get(status = d['a_status']) tags = d['tags'] del d['tags'] book = Book(**d) book.save() # must save item to generate Book.id before creating tags [book.tags.add(tag) for tag in tags] book.save() # save again after tags are generated
def add(request): if request.POST and request.POST['name']: form = Book(request.POST) if form.is_valid(): form.save() else: return render_to_response('book/add_book.html')
class RateViewTests(TestCase): def setUp(self): self.book = Book(isbn='85-359-0277-5', title='title', price=10, author='author', image='test.jpg') self.book.save() self.user = User(user_id=1, name='test') self.user.save() self.book2 = Book(isbn='0-306-40615-2', title='title', price=10, author='author', image='test.jpg') self.book2.save() rate = Rate(rating=1, book_id=self.book2, user_id=self.user) rate.save() def test_put_new_rate_should_return_201(self): """ When non existing rate, new one is added """ resp = self.client.put('/ebucxop/books/85-359-0277-5/ratings/me?format=json', {'rating': 3}, HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame'))) response_content = json.loads(resp.content) self.assertEqual(resp.status_code, 201) self.assertEquals('3', response_content['rating']) def test_put_existing_rate_should_return_200(self): """ When existing rate, old rate is updated and 200 returned """ resp = self.client.put('/ebucxop/books/0-306-40615-2/ratings/me?format=json', {'rating': u'3'}, HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame'))) self.assertEqual(resp.status_code, 200) response_content = json.loads(resp.content) # Ensure that 1 is changed to 3 self.assertEquals('3', response_content['rating'])
def add_book(request): booksurl = request.build_absolute_uri(reverse('books:index')) if request.method == 'POST': book_form = BookForm(request.POST) print(book_form.errors) if book_form.is_valid(): book_ISBN = book_form.cleaned_data['ISBN'] book_name = book_form.cleaned_data['name'] book_description = book_form.cleaned_data['description'] book_author = book_form.cleaned_data['author'] book_publication_year = book_form.cleaned_data['publication_year'] book_publisher = book_form.cleaned_data['publisher'] book_page_count = book_form.cleaned_data['page_count'] book_cover_URL = book_form.cleaned_data['cover_URL'] new_book = Book(ISBN=book_ISBN, name=book_name, description=book_description, author=book_author, publication_year=book_publication_year, publisher=book_publisher, page_count=book_page_count, cover_URL=book_cover_URL) new_book.save() return HttpResponseRedirect('/') else: book_form = BookForm() return render(request, 'books/add_book.html', { 'booksurl': booksurl, 'book_form': book_form })
def edit_image(request, id): book = Book.objects.get(id=id) if request.method == 'POST': user = get_user(request) image = request.FILES['image'] fs = FileSystemStorage() filename = fs.save(image.name, image) file_url = fs.url(filename) book = Book(id=id, image=file_url) book.save(update_fields=["image"]) context = { 'user': user, 'book': book, } return render(request, 'books/edit_image_res.html', context) else: # elif request.method == 'GET': user = get_user(request) image_form = EditImageForm(initial={ 'image': book.image, }) context = { 'user': user, 'image_form': image_form, 'book': book, } return render(request, 'books/edit_image.html', context)
def setUp(self): self.author1 = AuthorFactory(name='Author 1') self.author2 = AuthorFactory(name='Author 2') self.book = Book(title='MyBook') self.book.save() self.book.authors.add(self.author1.pk, self.author2.pk)
class BookRateSerializerTests(TestCase): def setUp(self): bookModel = {'isbn': '0-306-40615-2', 'title': 'title', 'price': 10, 'author': 'author', 'image': 'test.jpg'} # Adding serializer extra fields that not required in model self.book = Book(**bookModel) self.user = User(user_id='3', name='test') self.book.save() self.user.save() self.expectedRateData = {'user_id': self.user.pk, 'rating': 4} self.fullRateData = {'book_id': self.book, 'user_id': self.user, 'rating': 4} # Adding serializer extra fields that not required in model self.rate = Rate(**self.fullRateData) def test_retrieve_rate_should_work(self): """ We check that serialization an existing model is working """ serializer = BookRateSerializer(self.rate) # Check we have a correct dictionary serialized with python datatypes # book_id is excluded from serialization self.assertEquals(serializer.data, self.expectedRateData) def test_create_valid_rate_should_work(self): """ We check deserialization process of a dictionary where we get a valid object model with validations succeded """ serializer = RateSerializer(data={'rating': 4, 'user_id': self.user.pk, 'book_id': self.book.pk}) # Check validations works self.assertEquals(serializer.is_valid(), True) # Check object created is what we expect self.assertEquals(serializer.object, self.rate) self.assertEquals(serializer.data['rating'], 4)
def setUp(self): books = Book.objects.bulk_create([ Book( title="one", publication_date="1970-01-01", isbn="12345x", page_count=100, cover_photo="www.google.pl", publication_language="pl", ), Book( title="two", publication_date="1980-01-01", isbn="12346x", page_count=100, cover_photo="www.google.pl", publication_language="pl", ), Book( title="three", publication_date="1990-01-01", isbn="12347x", page_count=100, cover_photo="www.google.pl", publication_language="pl", ), ]) authors = Author.objects.bulk_create([ Author(name="Stephen King"), Author(name="Andriej Diakow"), Author(name="Dan Simmons"), ]) for author, book in zip(authors, books): book.authors.add(author)
def create_post(**message): """ Arguments: - `**message`: """ body = message['plain'] email = message['from'] subject = message['subject'] MailPost(body=body,email=email).save() try: user = getUser(email) if parseSubject(subject,'add'): try: pairs = pairBody(body) title = parsePairForKey(pairs,'book') friend_loan = parsePairForKey(pairs,'friend') book = Book(user=user,title=title,friend_loan=friend_loan) book.save() sendBook(book,user) except Exception as e1: sendError(email,e1) if parseSubject(subject,'report'): try: user = getUser(email) sendReport(user) except Exception as e2: sendError(email,e2) except Exception as e3: sendError(email,e3)
def post(self, request, *args, **kwargs): title = request.data.get('title') condition = request.data.get('condition') category = request.data.get('category') price = request.data.get('price') bookad_image = request.data.get('image') try: book = Book.objects.get(title=title) except ObjectDoesNotExist: title, description, author, _ = google_books.get_book_info(title) book_image = google_books.get_book_image(title) #TODO: Make the image in the book as book_image book = Book(title=title, description=description, author=author, category=category, image=bookad_image) book.save() book_ad = BookAD(book=book, user=request.user, price=price, ad_image=bookad_image) book_ad.save() return Response(status=HTTP_200_OK)
def _handle_json(self, jsonpath): """ Store books from a file in JSON format. """ jsonfile = open(jsonpath) data_list = json.loads(jsonfile.read()) for d in data_list: # Get a Django File from the given path: f = open(d['book_path']) d['book_file'] = File(f) del d['book_path'] if d.has_key('cover_path'): f_cover = open(d['cover_path']) d['cover_img'] = File(f_cover) del d['cover_path'] if d.has_key('a_status'): d['a_status'] = Status.objects.get(status = d['a_status']) tags = d['tags'] del d['tags'] book = Book(**d) try: book.save() # must save item to generate Book.id before creating tags [book.tags.add(tag) for tag in tags] book.save() # save again after tags are generated except IntegrityError as e: if str(e) == "column file_sha256sum is not unique": print "The book (", d['book_file'], ") was not saved because the file already exsists in the database." else: raise CommandError('Error adding file %s: %s' % (d['book_file'], sys.exc_info()[1]))
def test_models(self): data_dicts = set_up_data() self.assertTrue(Collection(data_dicts['c'])) self.assertTrue(Publisher(data_dicts['p'])) self.assertTrue(Author(data_dicts['a'])) self.assertTrue(Book(data_dicts['b1'])) self.assertTrue(Book(data_dicts['b2']))
def handle(self, *args, **options): with open('./books/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 test_book_list_view_GET(self): response = self.client.get(self.book_list_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'books/book_list.html') self.assertEquals(Book.objects.count(), 0) author = Author( fullName='Author' ) author.save() isbn = IndustryIdentifier( isbn='ISBN_10', identifier='1234567890' ) isbn.save() book = Book( title='Title', publishedDate='2019', pageCount=0, language='en', smallThumbnail='http://books.google.com/books/content?id=hFfhrCWiLSMC&printsec=frontcover&img=1&zoom=5&source=gbs_api', thumbnail='http://books.google.com/books/content?id=hFfhrCWiLSMC&printsec=frontcover&img=1&zoom=1&source=gbs_api' ) book.save() book.authors.add(author) book.industryIdentifiers.add(isbn) self.assertEquals(Book.objects.count(), 1)
def handle(self, *args, **options): # self.stdout.write(options['filepath']) with open(options["filepath"], "rt") as f: reader = csv.reader(f) next(reader) for row in reader: bookObject = Book( listTitle=row[0], title=row[3], source=row[1], isbn=row[2], author=row[4], illustrator=row[5], publisher=row[6], year=2015, pages=0, readingLevel=row[9], gradeLevel=row[10], nameOfReader=row[11], gender=row[12], genderExpression=row[13], age=0, ethnicity=row[15], disability=row[16], sexualOrientation=row[17], education=row[18], income=0, religion=row[20], geography=row[21], familyStatus=row[22], notesByReader=row[23], ) bookObject.save()
def _handle_json(self, collection): """ Store books from a file in JSON format. """ jsonpath = os.path.join(collection,'books.json') jsonfile = open(jsonpath) #data_list = json.loads(jsonfile.read()) txt=jsonfile.read() jsonfile.close() data_list = eval(txt) log = open('log','w') print 'items',len(data_list) for d in data_list: # Get a Django File from the given path: pth = os.path.join(collection,d['book_file']) if os.path.exists(pth): if len(d['book_file'])>0: lng = d['dc_language'] subprocess.call('cp '+ pth + ' ' + '/library/media/'+lng,shell=True) book = Book(**d) else: print >> log, 'book_file not found',str(d) continue else: print >> log, 'path not found', pth continue book.save() log.close()
def two_books(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): books = [ Book(bookid="jaM7DwAAQBAJ", title="Ender's Game", authors="Orson Scott Card", publisher="Tom Doherty Associates", published="2017-10-17", isbn="9780765394866", pages=448, language="en", description=("This engaging, collectible, miniature hardcover" " of the Orson Scott Card classic ...")), Book(bookid="UCJMRAAACAAJ", title="Elantris", authors="Brandon Sanderson", publisher="Gollancz", published="2011", isbn="9780575097445", pages=656, language="en", description=("Elantris was built on magic and it thrived. " "But then the magic began to fade ...")) ] Book.objects.bulk_create(books) added_titles = ["Ender's Game", "Elantris"] return Book.objects.filter(title__in=added_titles)
def add_book(request): if request.method == 'POST': name = request.POST.get('name') content = request.POST.get('content') book = Book(name=name, content=content) book.save() return JsonResponse({"code": 200, "msg": "success"})
class AdminBookViewTests(TestCase): def setUp(self): self.bookData = {'isbn': '85-359-0277-5', 'title': 'title', 'price': '10', 'author': 'author', 'image': 'test.jpg'} # We put user_id 2 as this would be the identifier of admin returned by TDA self.user = User(user_id=2, name='admin') self.user.save() self.book2 = Book(isbn='0-306-40615-2', title='title', price=10, author='author', image='test.jpg') self.book2.save() def test_create_new_book_return_201(self): resp = self.client.post('/ebucxop/books/', data=self.bookData, HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin'))) self.assertEqual(resp.status_code, 201) self.assertEquals('85-359-0277-5', resp.data['isbn']) def test_update_existing_book_return_200(self): resp = self.client.post('/ebucxop/books/0-306-40615-2/', data={'title': 'titleUpdated'}, HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin'))) self.assertEqual(resp.status_code, 200) self.assertEquals('titleUpdated', resp.data['title']) def test_create_new_book_without_credentials_return_403(self): resp = self.client.post('/ebucxop/books/', data=self.bookData, HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame'))) self.assertEqual(resp.status_code, 403)
def _handle_csv(self, csvpath): """ Store books from a file in CSV format. WARN: does not handle tags """ csvfile = open(csvpath) dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) # TODO: Figure out if this is a valid CSV file status_published = Status.objects.get(status="Published") for row in reader: path = row[0] title = row[1] author = row[2] summary = row[3] if os.path.exists(path): f = open(path) book = Book( book_file=File(f), a_title=title, a_author=author, a_summary=summary, a_status=status_published ) try: book.save() except: print "EXCEPTION SAVING FILE '%s': %s" % (path, sys.exc_info()[0]) else: print "FILE NOT FOUND '%s'" % path
def create_and_save_book(book): book_id = book["id"] title = book["volumeInfo"].get("title") authors = book["volumeInfo"].get("authors") published_date = book["volumeInfo"].get("publishedDate") categories = book["volumeInfo"].get("categories") average_rating = book["volumeInfo"].get("averageRating") ratings_count = book["volumeInfo"].get("ratingsCount") thumbnail = book["volumeInfo"].get("imageLinks") # If there is a thumbnail, normal has higher priority over small if thumbnail is not None: thumbnail = thumbnail.get("thumbnail", thumbnail.get("smallThumbnail")) published_date = parse_date(published_date) book = Book( book_id=book_id, title=title, published_date=published_date, average_rating=average_rating, ratings_count=ratings_count, thumbnail=thumbnail, ) book.save() create_and_add_authors(authors, book) create_and_add_categories(categories, book)
def add_book(request, book_id): """ For adding a new book in the Inventory by searching in Google Books """ try: book = Book.objects.get(book_id=book_id) increase_book(request, book_id) # return redirect('book_list') except: key = 'AIzaSyDwXeYjarTARFI9bfX8bs96rqt0R3VZkwk' url = "https://www.googleapis.com/books/v1/volumes/{}?key={}".format( book_id, key) response = requests.get(url) data = response.json() print(data) book_name = data['volumeInfo']['title'] authors = data['volumeInfo']['authors'] if authors is not None: authors = ", ".join(authors) new_book = Book(book_name=book_name, author=authors, book_id=book_id, copies=1) new_book.save() return redirect('book_list')
def addB(request): errors = [] authors = Author.objects.all() if request.method == 'POST': if not request.POST.get('ISBN',''): errors.append('请填写书籍ISBN。') if not request.POST.get('Title',''): errors.append('请填写书籍标题。') if not request.POST.get('Author',''): errors.append('请填写书籍作者。') if not request.POST.get('Publisher',''): errors.append('请填写书籍出版社。') if not request.POST.get('PublishDate',''): errors.append('请填写书籍出版日期。') if not request.POST.get('Price',''): errors.append('请填写书籍价格。') if not errors: post = request.POST name = post['Author'] temp = Author.objects.get(Name=name) book = Book(ISBN=post['ISBN'], Title=post['Title'], Publisher=post['Publisher'], PublishDate=post['PublishDate'], Price=post['Price'], Author=temp,) book.save() return render_to_response('edit_success.html',locals()) return render_to_response('addB.html',locals())
def _handle_csv(self, csvpath): """ Store books from a file in CSV format. """ csvfile = open(csvpath) dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) #TODO: Figure out if this is a valid CSV file for row in reader: path = row[0] title = row[1] author = row[2] summary = row[3] f = open(path) book = Book(book_file=File(f), a_title=title, a_author=author, a_summary=summary) book.save()
def setUp(self): self.author1 = AuthorFactory(name="Author 1") self.author2 = AuthorFactory(name="Author 2") self.book = Book(title="MyBook") self.book.save() self.book.authors.add(self.author1.pk, self.author2.pk)
def addbook(require): if require.POST: post=request.POST a=Author(AuthorID=post['AID'],Name=post['AN'],Age=post['AA'],Country=post['AC']) a.save() b=Book(ISBN=post['BI'],Price=post['BP'],Publishdate=post['BPD'],Publisher=post['BPE'],Title=post['BT'],AuthorID=a) b.save() return HttpResponseRedirect("/home/")
def setUp(self): # lets create authors and override their value self.author1 = AuthorFactory(name="Author 1") self.author2 = AuthorFactory(name="Author 2") self.book = Book(title="Book 1") self.book.save() self.book.authors.add(self.author1.pk, self.author2.pk)
def handle(self, *args, **options): authors = ['Yiyang', 'Yadel', 'Susan', 'Dav'] genders = ['male', 'female'] with open('books/sampleData.csv', 'rt') as f: reader = csv.reader(f) next(reader) for row in reader: if row[0] == '': row[0] = row[3] if row[1] == '': row[1] = 'dlab' if row[2] == '': row[2] = str(random.choice(range(int(1e12), int(1e13)))) if row[4] == '': row[4] = random.choice(authors) if row[5] == '': row[5] = random.choice(authors) if row[6] == '': row[6] = 'dlab' if row[7] == '': row[7] = str(datetime.date.today()) if row[8] == '': row[8] = str(random.choice(range(100))) if row[9] == '': row[9] = 'unknown' if row[10] == '': row[10] = 'unknown' if row[11] == '': row[11] = random.choice(authors) if row[12] == '': row[12] = random.choice(genders) if row[13] == '': row[13] = '' if row[14] == '': row[14] = str(random.choice(range(120))) if row[15] == '': row[15] = 'not specified' if row[16] == '': row[16] = 'None' if row[17] == '': row[17] = 'unknown' if row[18] == '': row[18] = 'Bachelor' if row[19] == '': row[19] = str(random.choice(range(int(1e5)))) if row[20] == '': row[20] = 'unknown' if row[21] == '': row[21] = 'United States' if row[22] == '': row[22] = 'Good' if row[23] == '': row[23] = 'None' bookObject = Book(listTitle=row[0], title=row[3], source=row[1], isbn=row[2], author=row[4], illustrator=row[5], publisher=row[6], year=row[7], pages=row[8], readingLevel=row[9], gradeLevel=row[10], nameOfReader=row[11], gender=row[12], genderExpression=row[13], age=row[14], ethnicity=row[15], disability=row[16], sexualOrientation=row[17], education=row[18], income=row[19], religion=row[20], geography=row[21], familyStatus=row[22], notesByReader=row[23]) bookObject.save()
def searchbooks(): booklist = {} searchterm = request.args.get('value') attr = request.args.get('refineSearch') if attr == "all": attr = None if searchterm is None: searchterm = "" else: searchterm = searchterm.lstrip() if searchterm is None or searchterm == "": pass else: cur_user = current_user() logging.info(cur_user) if not cur_user.is_authenticated(): #Assume no books in library or network, return results only booklist = Book.search_books_by_attribute(searchterm,attr) for book in booklist: booklist[book] = booklist[book].to_dict() #Assume not in booklist or networkbooklist booklist[book]["inLibrary"] = "False" booklist[book]["inNetwork"] = "False" else: user = current_user() #Create a dictionary of the user's books mybooklist = {} for copy in user.get_library(): mybooklist[copy.OLKey] = copy #Create a dictionary of the books in my network networkbooklist = {} string = "" for connection in user.get_connections(): u = UserAccount.getuser(connection.id()) for copy in u.get_library(): networkbooklist[copy.OLKey] = copy booklist = Book.search_books_by_attribute(searchterm,attr) for book in booklist: booklist[book] = booklist[book].to_dict() booklist[book]["escapedtitle"] = re.escape(booklist[book]["title"]) if booklist[book]['OLKey'] in mybooklist: booklist[book]["inLibrary"] = "True" else: booklist[book]["inLibrary"] = "False" if booklist[book]['OLKey'] in networkbooklist: booklist[book]["inNetwork"] = "True" else: booklist[book]["inNetwork"] = "False" return render_response('searchbooks.html', books=booklist, search=searchterm, attribute=attr)
def test_book_author(self): a1 = Author.objects.create(name='J.K. Rowling', birth_date='1965-07-31') b1 = Book(title='Harry Potter', num_pages=300, date_published='1997-06-26') b1.author = a1 b1.save() self.assertEqual(b1.author.name, 'J.K. Rowling')
def test_setCollaborators_should_setCollaboratorsAndSaveBook(self): _book = Book() _book.set_collaborators = mock.Mock() self.modelStub.from_legacy_model.return_value = _book self.sut.set_collaborators(Book(), []) self.assertTrue(_book.set_collaborators.called) self.repositoryStub.save.assert_called_with(_book)
def handle(self, *args, **options): with open(settings.BOOKS, encoding='utf-8') as file: reader = json.load(file) for book in reader: new_book = Book(name=book['fields']['name'], author=book['fields']['author'], pub_date=book['fields']['pub_date']) new_book.save()
def test_create_book_with_same_isbn_raises_error(self): publisher = PublisherFactory() author = AuthorFactory() book = BookFactory() new_book = Book( author=author, publisher=publisher, isbn=book.isbn, title='Test book' ) with self.assertRaises(IntegrityError): new_book.save()
def handle(self, *args, **options): series, created = Series.objects.get_or_create(name='freiesMagazin') binding, created = Binding.objects.get_or_create(name='E-Book') language, created = Language.objects.get_or_create(name='Deutsch') volume = Book.objects.filter(series=series).aggregate(Max('volume'))['volume__max'] if volume == None: volume = 0 month = (2006, 2) else: title = Book.objects.get(series=series, volume=volume).title month = (int(title[-4:]), int(title[-7:-5])) code = HTTP.OK while code == HTTP.OK: volume += 1 month = next(month) try: code = urlopen('http://www.freiesmagazin.de/freiesMagazin-%d-%02d' % (month[0], month[1])).code if code == HTTP.OK: self.stdout.write('Adding Issue %d (%02d/%d)...' % (volume, month[1], month[0])) book = Book(title='freiesMagazin %02d/%d' % (month[1], month[0]), series=series, volume=volume, binding=binding, published_on=date(year=month[0], month=month[1], day=1), purchased_on=date.today()) book.save() book.languages.add(language) book.save() folder = join(settings.MEDIA_ROOT, 'books', str(book.id)) if not exists(folder): makedirs(folder) image = join(folder, 'cover.jpg') try: urlretrieve('http://www.freiesmagazin.de/system/files/freiesmagazin-%d-%02d.png' % (month[0], month[1]), image) book.cover_image = image book.save() except HTTPError as e: pass name = slugify('freiesMagazin-%d-%02d' % (month[0], month[1])) + '.pdf' pdf = join(folder, name) urlretrieve('http://www.freiesmagazin.de/ftp/%d/freiesMagazin-%d-%02d.pdf' % (month[0], month[0], month[1]), pdf) EBookFile.objects.create(ebook_file=join('books', str(book.id), name), book=book) try: name = slugify('freiesMagazin-%d-%02d' % (month[0], month[1])) + '.epub' epub = join(folder, name) urlretrieve('http://www.freiesmagazin.de/ftp/%d/freiesMagazin-%d-%02d-bilder.epub' % (month[0], month[0], month[1]), epub) EBookFile.objects.create(ebook_file=join('books', str(book.id), name), book=book) except HTTPError as e: pass Url.objects.create(url='http://www.freiesmagazin.de/freiesMagazin-%d-%02d' % (month[0], month[1]), book=book) book.save() except HTTPError as e: self.stdout.write('No Issue %d (%02d/%d), stopping.' % (volume, month[1], month[0])) break
def handle(self, dirpath='', *args, **options): if not os.path.exists(dirpath): raise CommandError("%r is not a valid path" % dirpath) if os.path.isdir(dirpath): names = get_epubs(dirpath) for name in names: info = None try: e = Epub(name) info = e.get_info() except: print "%s is not a valid epub file" % name continue lang = Language.objects.filter(code=info.language) if not lang: for data in langs: if data[0] == info.language: lang = Language() lang.label = data[1] lang.save() break else: lang = lang[0] #XXX: Hacks below if not info.title: info.title = '' if not info.summary: info.summary = '' if not info.creator: info.creator = '' if not info.rights: info.rights = '' f = open(name) pub_status = Status.objects.get(status='Published') book = Book(book_file=File(f), a_title = info.title, \ a_author = info.creator, a_summary = info.summary, \ a_rights = info.rights, dc_identifier = info.identifier['value'].strip('urn:uuid:'), \ dc_issued = info.date, a_status = pub_status) try: book.save() # FIXME: Find a better way to do this. except IntegrityError as e: if str(e) == "column file_sha256sum is not unique": print "The book (", book.book_file, ") was not saved because the file already exsists in the database." else: raise CommandError('Error adding file %s: %s' % (book.book_file, sys.exc_info()[1])) except: raise CommandError('Error adding file %s: %s' % (book.book_file, sys.exc_info()[1]))
def test_create_book(self): book = Book( title='Capital in the Twenty-First Century', rate=5, have_read=True, is_favorite=True, review='Very interesting', ) book.save() self.assertIsInstance(book, Book) self.assertEquals(book.title, 'Capital in the Twenty-First Century')
def submit(request): name = request.POST['name'] genre = request.POST['genre'] author_id = request.POST['author'] author = Author.objects.get(pk=author_id) book = Book(name=name, genre=genre, author=author) book.save() books = Book.objects.all() return render(request, 'books/create.html', {'books': books})
def update_book_info(cls, book: Book, info_to_update: Dict[str, str]): author_data = {} for author in info_to_update['author']: temp = author.split(' ') author_data['name'], author_data['surname'] = temp[0], temp[-1] author = cls.add_author_to_db(author_data) book.author.add(author) if info_to_update.get('genre'): book.genre = cls.add_or_get_genre(info_to_update.get('genre')) book.description = info_to_update.get('annotation') book.save()
def handle(self, *args, **options): # self.stdout.write(options['filepath']) with open(options['filepath'], 'rt') as f: reader = csv.reader(f) next(reader) for row in reader: bookObject = Book(listTitle=row[0], title=row[3], source=row[1], isbn=row[2], author=row[4], illustrator=row[5], publisher=row[6], year=2015, pages=0, readingLevel=row[9], gradeLevel=row[10], nameOfReader=row[11], gender=row[12], genderExpression=row[13], age=0, ethnicity=row[15], disability=row[16], sexualOrientation=row[17], education=row[18], income=0, religion=row[20], geography=row[21], familyStatus=row[22], notesByReader=row[23]) bookObject.save()
def books_insert(request): if request.POST: post=request.POST newbook=Book( title = post["title"], authors_id = Author.objects.get(name=post["name"]).id, publisher = post["publisher"], publishdate = post["publishdate"], price = post["price"]) newbook.save() return render_to_response("books_insert.html")
def setUp(self): self.book = Book(isbn='85-359-0277-5', title='title', price=10, author='author', image='test.jpg') self.book.save() self.user = User(user_id=2, name='admin') self.user.save() self.book2 = Book(isbn='0-306-40615-2', title='title', price=20, author='author', image='test.jpg') self.book2.save() rate = Rate(rating=1, book_id=self.book2, user_id=self.user) rate.save()
class BookViewsTests(TestCase): def setUp(self): self.book = Book(isbn='85-359-0277-5', title='title', price=10, author='author', image='test.jpg') self.book.save() self.user = User(user_id=2, name='admin') self.user.save() self.book2 = Book(isbn='0-306-40615-2', title='title', price=20, author='author', image='test.jpg') self.book2.save() rate = Rate(rating=1, book_id=self.book2, user_id=self.user) rate.save() def test_get_existing_book_should_return_200(self): """ When non existing rate, new one is added """ resp = self.client.get('/ebucxop/books/85-359-0277-5?format=json', {}, HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin'))) response_content = json.loads(resp.content) self.assertEqual(resp.status_code, 200) self.assertEquals('10', response_content['price']) def test_get_existing_books_should_return_all_books(self): """ When non existing rate, new one is added """ resp = self.client.get('/ebucxop/books/?format=json', {}, HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin'))) response_content = json.loads(resp.content) self.assertEqual(resp.status_code, 200) self.assertEquals('10', response_content['results'][0]['price']) self.assertEquals('20', response_content['results'][1]['price']) def test_update_existing_book_price_should_return_200(self): """ When non existing rate, new one is added """ resp = self.client.post('/ebucxop/books/85-359-0277-5?format=json', {'price': 30}, HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('admin', 'admin'))) response_content = json.loads(resp.content) self.assertEqual(resp.status_code, 200) self.assertEquals('30', response_content['price']) def test_update_existing_book_with_invalid_credentials_should_return_200(self): """ When non existing rate, new one is added """ user = User(user_id=1, name='Aladdin') user.save() resp = self.client.put('/ebucxop/books/85-359-0277-5?format=json', {'price': 30}, HTTP_AUTHORIZATION='Basic ' + base64.b64encode('%s:%s' % ('Aladdin', 'open sesame'))) self.assertEqual(resp.status_code, 403)
def handle(self, *args, **options): faker = Faker("pl_PL") for i in range(10): book = Book() book.title = faker.text(50) book.isbn = faker.isbn13() book.pages = faker.random_number() book.cover_type = "soft" book.save() people = Author.objects.all() book.author.add(random.choice(people)) book.save() self.stdout.write(self.style.SUCCESS(f'Create:{book}'))
def addbooks(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: title = request.POST.get('title') author = request.POST.get('author') read = request.POST.get('read') b = Book(title=title, author=author, read=read) b.save() return HttpResponseRedirect('/admin/books') # if a GET (or any other method) we'll create a blank form else: return render_to_response('addBooks.html', '')
class BookTest(TestCase): def setUp(self): self.author1 = AuthorFactory(name='Author 1') self.author2 = AuthorFactory(name='Author 2') self.book = Book(title='MyBook') self.book.save() self.book.authors.add(self.author1.pk, self.author2.pk) def tearDown(self): self.author1.delete() self.author2.delete() self.book.delete()
def add_books(request): if(request.method == "POST"): copies = int(request.POST['number']) for x in xrange(0,copies): book = Book(name=request.POST['book'],author=request.POST['author']) book.slug = slugify(request.POST['book']) book.save() text = "Book/s Created" context = {'text': text} return render_to_response('addbooks.html', context, context_instance=RequestContext(request)) else: context = {} return render_to_response('addbooks.html', context, context_instance=RequestContext(request))
class BookTest(TestCase): # Django requires an explicit setup() when running tests in PTVS @classmethod def setUpClass(cls): django.setup() super(BookTest, cls).setUpClass() # setUp will run before each test def setUp(self): self.author1 = AuthorFactory(name="Author 1") self.author2 = AuthorFactory(name="Author 2") self.book = Book(title="MyBook") self.book.save() self.book.authors.add(self.author1.pk, self.author2.pk) # tearDown will run after each test def tearDown(self): self.author1.delete() self.author2.delete() self.book.delete() # UNIT TESTS def test_can_list_authors(self): self.assertEqual("Author 1, Author 2", self.book.list_authors()) def test_string_method(self): self.assertEqual("MyBook by Author 1, Author 2", self.book.__str__()) def test_custom_save_method(self): self.assertIsNone(self.book.date_reviewed) self.book.review = "My review" self.book.save() self.assertIsNotNone(self.book.date_reviewed)
def read_gutenberg_headers(fp): book = Book() for line in fp: if line.startswith('Title:'): book.title = line[6:].strip(string.punctuation + string.whitespace) if line.startswith('Author:'): book.author = line[7:].strip(string.punctuation + string.whitespace) if line.startswith('Release Date:'): book.published = line[13:].strip(string.punctuation + string.whitespace) if line.startswith('*** START OF THIS PROJECT GUTENBERG EBOOK'): return book
def post(self, request): form = books.forms.NewBookForm(request.POST) if form.is_valid(): # TODO: ModelForm? new_book = Book(user=request.user, title=form.cleaned_data['title'], url=form.cleaned_data['url'], privacy=form.cleaned_data['privacy'], pub_date=datetime.date.today()) new_book.save() return redirect('edit_book', book_pk=new_book.id) else: context = {'form': form} return render(request, 'books/new_book.html', context)
class BookTest(TestCase): def setUp(self): self.author1 = AuthorFactory(name="Author 1") self.author2 = AuthorFactory(name="Author 2") self.book = Book(title="MyBook") self.book.save() self.book.authors.add(self.author1.pk, self.author2.pk) def tearDown(self): self.author1.delete() self.author2.delete() self.book.delete() def test_can_list_authors(self): self.assertEqual("Author 1, Author 2", self.book.list_authors()) def test_string_method(self): self.assertEqual("MyBook by Author 1, Author 2", self.book.__str__()) def test_custom_save_method(self): self.assertIsNone(self.book.date_reviewed) self.book.review = "My Review" self.book.save() self.assertIsNotNone(self.book.date_reviewed)
def add_author_a(request): AuthorID = request.GET['AuthorID'] Name = glob.Author_name Age = request.GET['Age'] Country = request.GET['Country'] if not AuthorID: return render_to_response('No_in.html') else: auth_add = Author(AuthorID = AuthorID, Name = Name, Age = Age, Country = Country) auth_add.save() book_add = Book(ISBN = glob.ISBN,Title = glob.Title,AuthorID = Author.objects.get(Name = Name),Publisher = glob.Publisher,\ PublishDate = glob.PublishDate, Price = glob.Price) book_add.save() return render_to_response('First_page.html')
def _handle_json(self, jsonpath): """ Store books from a file in JSON format. """ jsonfile = open(jsonpath) data_list = json.loads(jsonfile.read()) for d in data_list: # Get a Django File from the given path: f = open(d['book_path']) d['book_file'] = File(f) del d['book_path'] book = Book(**d) book.save()
def handle(self, *args, **options): for filename in os.listdir('files'): filename = os.path.join('files',filename) if os.path.isfile(filename): with open(filename, "rb") as f: b = Book() b.image = File(f) thumbnail = os.path.join(os.path.dirname(filename), 'thumbnails', os.path.splitext(os.path.basename(filename))[0] + '.png') with open(thumbnail, "rb") as tn: b.thumbnail = File(tn) b.save() shutil.move(filename, "files/done")