class BookViewSetTests(TestCase): def setUp(self): self.book = Book() self.book.title = "some_book" self.book.publishing_year = 2000 self.book.isbn = "123456" self.book.save() def test_get(self): response = self.client.get(f'/api/book/books/', {'pk': self.book.pk}, follow=True) serializer = BookSerializer(self.book, many=False) expected = [collections.OrderedDict(serializer.data)] self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 1) self.assertEqual(response.data, expected) def test_basic_view_get(self): response = self.client.get(f'/api/book/books/', {'title': 'some_book'}, follow=True) serializer = BookSerializer(self.book, many=False) expected = [collections.OrderedDict(serializer.data)] self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 1) self.assertEqual(response.data, expected)
def approve_suggestion(request,pk): suggestion = BookSuggestion.objects.get(pk=pk) categories = Category.objects.all() if request.method == 'POST': form = BookForm(request.POST) book = Book() if form.is_valid(): book.title = form.cleaned_data['title'] book.author = form.cleaned_data['author'] book.url = form.cleaned_data['url'] book.description = form.cleaned_data['description'] book.image_url = form.cleaned_data['image_url'] book.save() book.category.clear() for category in form.cleaned_data['category']: book.category.add(category.id) book.save() suggestion.delete() return redirect(to='suggestions') else: form = BookForm() return render(request, 'core/approve_suggestion.html', { 'suggestion' : suggestion, 'form' : form, 'categories' : categories, })
def parse_csv(path_to_csv): from core.models import Book from django.contrib.auth import get_user_model # from django.contrib.auth.models import User User = get_user_model() User.objects.filter(is_staff=False).delete() Book.objects.all().delete() # User.objects.create_superuser("tema", "*****@*****.**", "123321") authors_buffer = {} similar_buffer = {} with open(path_to_csv, newline='') as f: booksreader = csv.DictReader(f) for i, book in enumerate(booksreader): if i > 100: break authors = book["authors"][:150] name = book["original_title"] if authors == "" or name == "": continue rating_string = book["average_rating"] if authors not in authors_buffer: user = User.objects.create_user(username=authors) authors_buffer[authors] = user else: user = authors_buffer[authors] book_instance = Book(name=name, author=user, genre=makeup_genre(i, book), written=date_from_year( book["original_publication_year"]), is_published=makeup_published(i), rating=book["average_rating"], price=book["books_count"], object_id=make_object_id(book["isbn"])) try: book_instance.save() similar_books = similar_buffer.setdefault(rating_string, []) if len(similar_books) > 0: book_instance.similar_books.add(*similar_books) similar_books.append(book_instance) except: print("Error saving %s" % book_instance.name) book_instance.save()
def build_book_object_based_on_isbn(isbn, save=False): response = rlibrary.settings.GOOGLE_BOOK_API.list(isbn) item = response["items"][0] volume_info = item["volumeInfo"] if "subtitle" in volume_info: title = "{} - {}".format(volume_info["title"], volume_info["subtitle"]) else: title = "{}".format(volume_info["title"]) publisher = volume_info.get("publisher", "") published_date = dateparser.parse(volume_info["publishedDate"]) language = volume_info["language"] categories = volume_info.get("categories", []) authors = volume_info["authors"] isbn = isbn if "imageLinks" in volume_info: thumbnail = volume_info["imageLinks"].get("smallThumbnail", "") else: thumbnail = "" authors_obj = [] tags = [] for author in authors: author_obj = Author.objects.get_or_create(full_name=author)[0] authors_obj.append(author_obj) for category in categories: tag = Tag.objects.get_or_create(name=category)[0] tags.append(tag) language = Language.objects.get_or_create(code=language)[0] data = { # "authors": authors_obj, "title": title, "isbn": isbn, "publisher": publisher, "published_date": published_date, # "tags": tags, "language": language, "thumbnail": thumbnail, } book = Book(**data) if save is True: for author in authors_obj: author.save() book.authors.add(author) for tag in tags: tag.save() book.tags.add(tag) book.save() return {"book": book, "authors": authors_obj, "tags": tags}
def add_book(request): new_book = Book() categories = Category.objects.all() if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): new_book.title = form.cleaned_data['title'] new_book.author = form.cleaned_data['author'] new_book.url = form.cleaned_data['url'] new_book.description = form.cleaned_data['description'] new_book.image_url = form.cleaned_data['image_url'] new_book.save() for category in form.cleaned_data['category']: new_book.category.add(category.id) new_book.save() return redirect(to='staff') else: form = BookForm() return render(request, 'core/add_book.html', { 'new_book' : new_book, 'form' : form, 'categories' : categories, })
num_awards=num_awards, ) ''' Cadastra os livros ''' publisher = Publisher.objects.get(name=name_publisher) name_book = book_list[i]['name'] try: ''' Com get pega o nome do livro. ''' book = Book.objects.get(name=name_book) ''' Inserindo os autores nos livros ''' author = Author.objects.get(name=name_author) book.authors.add(author) except ObjectDoesNotExist: ''' Se não existir, então cria o livro. ''' book_obj = Book( isbn=random.randint(1, 9999999999), name=name_book, rating=gen_decimal(3, 2), # author=author, publisher=publisher, price=gen_decimal(3, 2), stock_min=random.randint(1, 100), stock=random.randint(1, 1000), ) book_obj.save() ''' Inserindo os autores nos livros ''' book = Book.objects.get(pk=book_obj.id) author = Author.objects.get(name=name_author) book.authors.add(author) print('%d Books salvo com sucesso.' % REPEAT)
else: book_cover = "" new_book = Book( author_last_name=book[1], author_first_name=book[2], title=book[3], dewey_decimal=book[4], topic=book[5], category=book[6], year_acquired=int(book[7]), publisher=book[8], cover=book_cover, num_pages=int(book[10]) if book[10] != '' else 0, is_fiction=fiction ) new_book.save() book_map.append((book[0], new_book.pk)) patron_map = [] for patron in patrons: new_patron = Patron( last_name=patron[1], first_names=patron[2], address=patron[3], city=patron[4], postal=patron[5], phone=patron[6], alt_phone=patron[7], email=patron[8], alt_email=patron[9] ) new_patron.save()
def handle(self, *args, **options): # process argument (module code) if not args: print 'Usage: python manage.py refresh <module_code> --option' return # info timestr = time.strftime("%Y.%m.%d.%H.%M.%S") out.info('Logging started at %s', timestr) # out.info('SITE_ROOT = %s' % SITE_ROOT) # out.info('TEX_ROOT = %s' % TEX_ROOT) # iterate over modules for module_code in args: out.info('BEGIN processing %s', module_code) # find main.tex main_tex = os.path.join(TEX_ROOT, module_code, 'main.tex') # parse p = TexParser() tree = p.parse_book(main_tex) # text output (native format) if options['text']: print tree # xml output if options['xml']: xml = tree.prettyprint_xml() self.stdout.write(xml) # labels if options['labels']: pairs = tree.get_label_mpaths() col_width = max([len(pair[0]) for pair in pairs]) + 2 # padding for pair in pairs: self.stdout.write(pair[0].ljust(col_width) + pair[1]) # database if options['db'] or options['commit']: # check whether this module already exists in the database preamble = p.parse_preamble(main_tex) code = preamble['module_code'] year = preamble['academic_year'] module = Module.objects.filter(code=code, year=year).first() if not module: out.info('Creating new module %s/%s' % (code, year)) module = Module(code=code, year=year, title=preamble['module_title']) module.save() else: out.info('Updating existing module %s/%s' % (code, year)) number = preamble['book_number'] book = Book.objects.filter(module=module, number=number).first() if book: out.info('Existing book %s/%s/%s will be deleted' % (code, year, number)) for booknode in BookNode.objects.filter( mpath__startswith=book.tree.mpath): booknode.delete() book.delete() book = Book() code = preamble['module_code'] year = preamble['academic_year'] book.module = Module.objects.filter(code=code, year=year).first() if 'book_number' in preamble: book.number = int(preamble['book_number']) else: book.number = 0 if 'book_title' in preamble: book.title = preamble['book_title'] if 'book_author' in preamble: book.author = preamble['book_author'] if 'book_version' in preamble: book.version = preamble['book_version'] if 'new_commands' in preamble: book.new_commands = preamble['new_commands'] hexstr = hex(book.number)[2:].zfill(2) prefix = code + '.' + hexstr # write book database if options['commit']: book.tree = tree.write_to_camel_database(prefix=prefix, commit=True) book.save() else: tree.write_to_camel_database(prefix=prefix, commit=False) # write labels to database pairs = tree.get_label_mpaths() for pair in pairs: lab = Label() lab.text = prefix + '.' + pair[0] lab.mpath = prefix + pair[1] if options['commit']: lab.book = book lab.save() else: print lab
def handle(self, *args, **options): # process argument (module code) if not args: print 'Usage: python manage.py refresh <module_code> --option' return # info timestr = time.strftime("%Y.%m.%d.%H.%M.%S") out.info('Logging started at %s', timestr) # out.info('SITE_ROOT = %s' % SITE_ROOT) # out.info('TEX_ROOT = %s' % TEX_ROOT) # iterate over modules for module_code in args: out.info('BEGIN processing %s', module_code) # find main.tex main_tex = os.path.join(TEX_ROOT, module_code, 'main.tex') # create book tree p = TexParser() preamble = p.parse_preamble( main_tex ) book = p.parse_book( main_tex ) book.title = preamble['book_title'] # xml output if options['xml']: xml = book.prettyprint_xml() self.stdout.write( xml ) # labels elif options['labels']: pairs = book.get_label_mpaths() col_width = max( [len(pair[0]) for pair in pairs] ) + 2 # padding for pair in pairs: self.stdout.write( pair[0].ljust(col_width) + pair[1] ) # camel database output if options['db']: # check whether this module already exists in the database preamble = p.parse_preamble( main_tex ) code = preamble['module_code'] year = preamble['academic_year'] module = Module.objects.filter(code=code, year=year).first() if not module: out.warning( 'Module %s/%s does not exist - do nothing' % (code, year) ) # out.info( 'Creating new module %s/%s' % (code, year) ) # module = Module(code=code, year=year, title=preamble['module_title']) # module.save() else: out.info( 'Updating existing module %s/%s' % (code, year) ) number = preamble['book_number'] bk = Book.objects.filter(module=module, number=number).first() if bk: out.info( 'Existing book %s/%s/%s will be deleted' % (code, year, number) ) for booknode in BookNode.objects.filter(mpath__startswith=bk.tree.mpath): booknode.delete() bk.delete() cbook = Book() code = preamble['module_code'] year = preamble['academic_year'] cbook.module = Module.objects.filter(code=code, year=year).first() if 'book_number' in preamble: cbook.number = int(preamble['book_number']) else: cbook.number = 0 if 'book_title' in preamble: cbook.title = preamble['book_title'] if 'book_author' in preamble: cbook.author = preamble['book_author'] if 'book_version' in preamble: cbook.version = preamble['book_version'] if 'new_commands' in preamble: cbook.new_commands = preamble['new_commands'] hexstr = hex( cbook.number )[2:].zfill(2) prefix = code + '.' + hexstr # write book database cbook.tree = book.write_to_camel_database(prefix=prefix, commit=True) cbook.save() # write labels to database pairs = book.get_label_mpaths() for pair in pairs: lab = Label() lab.book = cbook lab.text = prefix + '.' + pair[0] lab.mpath = prefix + pair[1] lab.save() print lab