def post(self): data = request.json name = data.get('name') category = data.get('category') price = data.get('price') user_id = 1 # Todo: Get user_id from cookie is_exist = Book.query.filter_by(name=name).first() if is_exist: jsonify({ 'code': '-1', 'msg': "Add book failed", 'error': "book with this name existed" }) book = Book(name, category, price, user_id) db.session.add(book) err = book.session_commit() if not err: book = Book.query.filter_by(name=name).first() return jsonify({ 'code': '0', 'data': book.to_dict(), 'msg': 'success' }) return jsonify({'code': '-1', 'msg': 'add book failed', 'error': err})
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 book_edit(request, book_id=None): msg = False if book_id: book = get_object_or_404(Book, pk=book_id) submit_text = "Update" submit_url = reverse("dashboard:book_edit",kwargs={'book_id':book.id}) else: book = Book() submit_text = "Add New" submit_url = reverse("dashboard:book_add") if request.method == 'POST': form = forms.BookForm(request.POST, instance=book) if form.is_valid(): book_new = form.save(commit=False) book_new.owner = get_login_user(request.user.id) book_new.save() return redirect('dashboard:book_index') else: print("validation fail") else: form = forms.BookForm(instance=book) return render(request, 'dashboard/book/edit.html', {'msg': msg, 'form':form, 'book': book, 'submit_text': submit_text, 'submit_url': submit_url})
def do_update(): print("\ndo_update()") # clearing down existing objects Book.objects.all().delete() rows = [('', 'Some new book', '*****@*****.**', '10.25')] * NUM_ROWS books = [Book(name=r[1], author_email=r[2], price=r[3]) for r in rows] # run 'update' - there must be existing rows in the DB... # i.e. so they can be updated Book.objects.bulk_create(books) assert NUM_ROWS == Book.objects.count() # find the ids, so that we can perform the update all_books = Book.objects.all() rows = [(b.id, b.name, b.author_email, b.price) for b in all_books] dataset = tablib.Dataset(*rows, headers=['id', 'name', 'author_email', 'price']) book_resource = _BookResource() do_import_duration(book_resource, dataset) do_import_mem(book_resource, dataset) assert NUM_ROWS == Book.objects.count() Book.objects.all().delete()
def book_edit(request, book_id=None): msg = False if book_id: book = get_object_or_404(Book, pk=book_id) submit_text = "Update" submit_url = reverse("core:book_edit", kwargs={"book_id": book.id}) else: book = Book() submit_text = "Add New" submit_url = reverse("core:book_add") if request.method == "POST": form = forms.BookForm(request.POST, instance=book) if form.is_valid(): book_new = form.save(commit=False) book_new.owner = get_login_user(request.user.id) book_new.save() return redirect("core:book_detail", book.id) else: print("validation fail") else: form = forms.BookForm(instance=book) return render( request, "dashboard/book/edit.html", { "msg": msg, "form": form, "book": book, "submit_text": submit_text, "submit_url": submit_url, }, )
def do_delete(): # Run this twice - once for duration and once for memory counts # comment out the lines in profile() as appropriate class _BookResource(resources.ModelResource): def for_delete(self, row, instance): return True class Meta: model = Book fields = ('id', 'name', 'author_email', 'price') use_bulk = True batch_size = 1000 skip_diff = True instance_loader_class = CachedInstanceLoader rows = [('', 'Some new book', '*****@*****.**', '10.25')] * NUM_ROWS books = [Book(name=r[1], author_email=r[2], price=r[3]) for r in rows] Book.objects.bulk_create(books) assert NUM_ROWS == Book.objects.count() # deletes - there must be existing rows in the DB... # i.e. so they can be deleted all_books = Book.objects.all() rows = [(b.id, b.name, b.author_email, b.price) for b in all_books] dataset = tablib.Dataset(*rows, headers=['id', 'name', 'author_email', 'price']) book_resource = _BookResource() do_import(book_resource, dataset)
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 test_get_diff(self): book2 = Book(name="Some other book") diff = self.resource.get_diff(self.book, book2) headers = self.resource.get_export_headers() self.assertEqual(diff[headers.index('name')], u'<span>Some </span><ins style="background:#e6ffe6;">' u'other </ins><span>book</span>') self.assertFalse(diff[headers.index('author_email')])
def do_delete(): class _BookResource(resources.ModelResource): def for_delete(self, row, instance): return True class Meta: model = Book fields = ('id', 'name', 'author_email', 'price') use_bulk = True batch_size = 1000 skip_diff = True instance_loader_class = CachedInstanceLoader print("\ndo_delete()") # clearing down existing objects Book.objects.all().delete() rows = [('', 'Some new book', '*****@*****.**', '10.25')] * NUM_ROWS books = [Book(name=r[1], author_email=r[2], price=r[3]) for r in rows] # deletes - there must be existing rows in the DB... # i.e. so they can be deleted Book.objects.bulk_create(books) assert NUM_ROWS == Book.objects.count() all_books = Book.objects.all() rows = [(b.id, b.name, b.author_email, b.price) for b in all_books] dataset = tablib.Dataset(*rows, headers=['id', 'name', 'author_email', 'price']) book_resource = _BookResource() do_import_duration(book_resource, dataset) assert 0 == Book.objects.count() # recreate rows which have just been deleted Book.objects.bulk_create(books) assert NUM_ROWS == Book.objects.count() all_books = Book.objects.all() rows = [(b.id, b.name, b.author_email, b.price) for b in all_books] dataset = tablib.Dataset(*rows, headers=['id', 'name', 'author_email', 'price']) do_import_mem(book_resource, dataset) assert 0 == Book.objects.count()
def do_update(): rows = [('', 'Some new book', '*****@*****.**', '10.25')] * NUM_ROWS books = [Book(name=r[1], author_email=r[2], price=r[3]) for r in rows] Book.objects.bulk_create(books) assert NUM_ROWS == Book.objects.count() # deletes - there must be existing rows in the DB... # i.e. so they can be deleted all_books = Book.objects.all() rows = [(b.id, b.name, b.author_email, b.price) for b in all_books] # Add this line in order to perform bulk delete dataset = tablib.Dataset(*rows, headers=['id', 'name', 'author_email', 'price']) book_resource = _BookResource() do_import(book_resource, dataset) assert Book.objects.count() == NUM_ROWS Book.objects.all().delete()
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 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
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)
def setUp(self): self.book = Book() self.book.title = "some_book" self.book.publishing_year = 2000 self.book.isbn = "123456" self.book.save()
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 test_add_instance_info_no_instance_pk(self): row_result = RowResult() row_result.add_instance_info(Book()) self.assertEqual(None, row_result.object_id) self.assertEqual("", row_result.object_repr)
book_map = [] for book in books: fiction = (int(book[11]) == 1) if book[11] != '' else 0 if book[9] == "HARD": book_cover = 'H' elif book[9] == "SOFT": book_cover = 'S' 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],
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 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, })