def account(): if current_user.role != 'admin': form = UpdateAccountForm() if form.validate_on_submit(): form.validate_name(form.name) form.validate_email(form.email) current_user.name = form.name.data current_user.email = form.email.data db.session.commit() flash('Reader account has been updated', 'success') else: form.name.data = current_user.name form.email.data = current_user.email # return render_template('account.html', title='Account', form=form) else: form = BookForm() if form.validate_on_submit(): books = Book.query.filter_by(title=form.title.data).all() for book in books: if book.author == form.author.data: flash('This book is already in the database', 'danger') else: book = Book() book.title = form.title.data book.author = form.author.data book.summary = form.summary.data db.session.add(book) db.session.commit() flash(f'Added book {book.title}', 'success') form.title.data = '' form.author.data = '' form.summary.data = '' return render_template('account.html', title='Account', form=form)
def get_added_books(delta_entries, user_id, client): """ Return a list of Books. All books in this list have the correct mimetype, are under the size limit, and don't have a duplicate hash in the database (i.e. not a filepath rename). """ added_entries = [] for entry in delta_entries: pathname, metadata = entry pathname = canonicalize(pathname) # First check that it's not a removed pathname. if metadata is None: continue # Check that pathname is a file, has an okay mimetype and is under the # size limit. if metadata["is_dir"] or not mimetypes_filter(pathname) or metadata["bytes"] > AMAZON_SIZE_LIMIT: continue book = Book(user_id, pathname, download_book(client, pathname, user_id), metadata["bytes"]) # NOTE: It's possible that the book failed to download here, in which # case `book_hash` is None. We still add it to the database in case it # can be downloaded later. db.session.add(book) # Make sure that the book is not a duplicate of a previously added book # (probably a renamed file). duplicate = Book.query.filter_by(user_id=user_id).filter_by(book_hash=book.book_hash).first() if duplicate is not None: book.unsent = duplicate.unsent continue added_entries.append(book) return added_entries
def add_book(): form = BookForm() if form.validate_on_submit(): if request.method == 'POST': existing_book = Book.query.filter( Book.name == form.name.data).filter( Book.author == form.author.data).first() book = Book(name=form.name.data, author=form.author.data) if (existing_book == None): book.create_time = datetime.utcnow() db.session.add(book) elif (current_user not in book.user): book.user.append(current_user) book.create_time = datetime.utcnow() else: flash('Book already exists!') return redirect(url_for('add_book')) # return redirect(url_for('add_book')) #and(existing_book.name == form.name.data and existing_book.author == form.author.data and existing_book.user_id == current_user.id)): # flash('Book already exists!') # return redirect(url_for('add_book')) db.session.commit() flash('Your book succesfully added!') return redirect(url_for('index')) return render_template("add_book.html", title='Add_book', form=form)
def init_db(): db.create_all() user1 = User(first_name="Albert", last_name="Einstein", email="*****@*****.**") user2 = User(first_name="Enrico", last_name="Fermi", email="*****@*****.**") user3 = User(first_name="Paul", last_name="Dirac", email="*****@*****.**") user4 = User(first_name="Werner", last_name="Heisenberg", email="*****@*****.**") book1 = Book(title="Harry Potter and the Sorcerer's Stone") book2 = Book(title="Harry Potter and the Chamber of Secrets") book3 = Book(title="Harry Potter and the Prisoner of Azkaban") user1.books.append(book1) user2.books.append(book1) book2.owners.append(user3) book2.owners.append(user1) book2.owners.append(user4) for ob in [user1, user2, user3, user4, book1, book2, book3]: ob.save() end yield db db.drop_all()
def test_send_book_list_email(self): u = User(username='******', email='*****@*****.**') b1title = 'hello' b2title = 'world' b1 = Book(title=b1title, author='b', date_of_purchase=datetime.utcnow(), notes='Test Notes') b2 = Book(title=b2title, author='d', date_of_purchase=datetime.utcnow(), notes='Test Notes') db.session.add(u) db.session.add(b1) db.session.add(b2) db.session.commit() u.add_book_owned(b1) u.add_book_owned(b2) db.session.commit() b = u.owned_books() subject = 'test' sender = '*****@*****.**' recipients = '*****@*****.**' text_body = 'text mctest' html_body = '<div>testing</div>' mail = Mail(self.app) with mail.record_messages() as outbox: send_book_list_email(u, recipients, b) assert len(outbox) == 1 book1 = outbox[0].body.find('hello') book2 = outbox[0].body.find('world') assert book1 > 0 assert book2 > 0
def get_added_books(delta_entries, user_id, client): """ Return a list of Books. All books in this list have the correct mimetype, are under the size limit, and don't have a duplicate hash in the database (i.e. not a filepath rename). """ added_entries = [] for entry in delta_entries: pathname, metadata = entry pathname = canonicalize(pathname) # First check that it's not a removed pathname. if metadata is None: continue # Check that pathname is a file, has an okay mimetype and is under the # size limit. if (metadata['is_dir'] or not mimetypes_filter(pathname) or metadata['bytes'] > AMAZON_SIZE_LIMIT): continue book = Book(user_id, pathname, metadata['bytes']) download_book(client, book, u'kindlebox') # Make sure that the book is not a duplicate of a previously added book # (probably a renamed file). duplicate = (Book.query.filter_by(user_id=user_id).filter_by( book_hash=book.book_hash).first()) if (duplicate is not None): book.unsent = duplicate.unsent added_entries.append(book) return added_entries
def test_borrow_book(mocker): # Testing with Invalid member mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id') mocker_model_get_by_id.side_effect = [None, None] with pytest.raises(MemberNotFound): borrow_book(1, 2) # Testing with Invalid Book mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id') mocker_model_get_by_id.side_effect = [Member(), None] with pytest.raises(BookNotFound): borrow_book(1, 2) # Testing with Already Taken Book mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id') mocker_model_get_by_id.side_effect = [Member(), Book(taken=True)] with pytest.raises(BookAlreadyTaken): borrow_book(1, 2) # Testing proper calling of function mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id') book = Book(taken=False) mocker_model_get_by_id.side_effect = [Member(), book] mocker_model_put = mocker.patch('google.cloud.ndb.Model.put') borrow_book(1, 2) assert book.taken == True mocker_model_put.assert_called_once()
def find_book(request): """ Generates list with books of data which user entered. At first it check full equality in name, after tries to check if contains some part of entered data. """ validate_api_secret_key(request.data.get('app_key')) request_serializer = FindBookRequest(data=request.data) if request_serializer.is_valid(): user = get_object_or_404(TheUser, auth_token=request.data.get('user_token')) search_data = request.data.get('search_term') filtered_books = Book.exclude_private_books( user.id_user, Book.fetch_books(search_data)) paginator = Paginator(filtered_books, OUTPUT_BOOKS_PER_PAGE) page = paginator.page(request.data.get('page')) next_page = page.has_next() page_books = page.object_list return Response( { 'detail': 'successful', 'data': { 'books': [BookSerializer(book).data for book in page_books], 'next_page': page.next_page_number() if next_page else 0 } }, status=status.HTTP_200_OK) else: return invalid_data_response(request_serializer)
def testSearchBookByName(self): response = self.client.post(url_for('main.index'), data={'name': 't'}) self.assertTrue(response.status_code == 302) response = self.client.post(url_for('main.index'), data={'name': 't'}, follow_redirects=True) self.assertTrue(response.status_code == 200) self.assertTrue('No records found' in response.get_data(as_text=True)) category_one = Category(name='One') category_two = Category(name='Two') db.session.add_all([category_one, category_two]) db.session.commit() book_one = Book(name='New World Order', category=category_one) book_two = Book(name='Things Fall Apart', category=category_two) book_three = Book(name='Pinkberry', category=category_two) book_four = Book(name='New Scopes', category=category_two) db.session.add_all([book_one, book_two, book_three, book_four]) db.session.commit() response = self.client.post(url_for('main.index'), data={'name': 't'}, follow_redirects=True) self.assertTrue(response.status_code == 200) self.assertTrue('Things Fall Apart' in response.get_data(as_text=True))
def moveBooksDataFromTables(): # carturesti_books = BooksCarturesti.query.all() carturesti_books = Book.query.all() for book in carturesti_books: new_book = Book( title=book.title, author=book.author, isbn=book.isbn, link=book.link, editura=book.editura, price=book.price, # img=book.img, library_id=1) db.session.add(new_book) db.session.commit() librarie_net_books = LibrarieNet.query.all() for book in librarie_net_books: new_book = Book( title=book.title, # author=book.author, isbn=book.isbn, link=book.link, # editura=book.editura, price=book.price, img=book.img, library_id=2) db.session.add(new_book) db.session.commit()
def editbook(request, book_id): if request.user.is_authenticated(): if request.session['user'] == 'admin': if request.method == 'GET': print(request.GET) if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): cd = form.cleaned_data post = Book(id=book_id, title=cd['title'], about=cd['about'], timestamp=cd['timestamp']) post.save() return HttpResponseRedirect('../../books') else: ctx = Context({'form': form}) ctx.update(csrf(request)) return render_to_response('app/book_form.html', ctx) else: post = Book.objects.get(id=int(book_id)) data = {'title': post.title, 'about': post.about} post_form = BookForm(initial=data) ctx = Context({'form': post_form}) ctx.update(csrf(request)) return render_to_response('app/book_form.html', ctx) else: return render_to_response('app/index.html'); else: return render_to_response('app/index.html');
def create(request): if request.method == "GET": form = BookForms() return render(request, 'Library/book.html', {"form": form}) if request.method == "POST": form = BookForms(request.POST) if form.is_valid(): obj = Book() obj.name = form.cleaned_data["name"] obj.isbn = form.cleaned_data["isbn"] obj.published_date = form.cleaned_data["published_date"] obj.pages = form.cleaned_data["pages"] obj.save() #for e in form.cleaned_data["authors"]: obj.authors.set(form.cleaned_data["authors"]) obj.save() return render( request, 'Library/book.html', { "form": BookForms(), "msg": { "status": "success", "msg": "Se añadio el libro" } }) return render(request, 'Library/book.html', {"form": form})
def deploy(): """Run deployment tasks.""" from flask.ext.migrate import upgrade from app.models import Author, Book, User upgrade() Author.add_authors() Book.add_books() User.add_admin()
def testCanFindBooksInCategory(self): tech = Category(name='tech') book = Book(name='Clean Code', category=tech) book2 = Book(name='Eloquent JavaScript', category=tech) db.session.add_all([book, book2, tech]) db.session.commit() books = Book.query.filter_by(category=tech).all() self.assertIsNotNone(books)
def create_books(): book1 = Book(title='Flask Web Dev 2e') book2 = Book(title='The New And Improved Flask Mega') book3 = Book(title='Complete Web Application') db.session.add(book1) db.session.add(book2) db.session.add(book3) db.session.commit()
def test_follow_posts(self): # create users and books u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') b1 = Book(title='Gone with the wind', author='Margaret Mitchell') b2 = Book(title='A tale of 2 cities', author='Charles Dickens') b3 = Book(title='Conspiration', author='Dan Brown') db.session.add(u1) db.session.add(u2) db.session.add(u3) db.session.add(u4) db.session.add(b1) db.session.add(b2) db.session.add(b3) db.session.commit() # create four posts now = datetime.utcnow() p1 = Post(body="post from john", user=u1, book=b1, timestamp=now + timedelta(seconds=1), level=1) p2 = Post(body="post from susan", user=u2, book=b2, timestamp=now + timedelta(seconds=4), level=1) p3 = Post(body="post from mary", user=u3, book=b2, timestamp=now + timedelta(seconds=3), level=1) p4 = Post(body="post from david", user=u4, book=b3, timestamp=now + timedelta(seconds=2), level=1) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup the followers u1.follow(b1) u1.follow(b2) u1.follow(b3) u2.follow(b1) db.session.commit() # check the followed posts of each user f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() self.assertEqual(f1, [p2, p3, p4, p1]) self.assertEqual(f2, [p1])
def setUp(self): self.admin = User.objects.get(pk=1) self.book1 = Book(pk=1, title="foo", body="foofoofoo", author=self.admin) self.book1.save() self.book2 = Book(pk=2, title="bar", body="barbarbar", author=self.admin) self.book2.save() # Delete TaggedItem everytime TaggedItem.objects.all().delete()
def create_book(): book_info = request.json or request.form book = Book(name=book_info.get('name'), author_id=book_info.get('author')) db.session.add(book) db.session.commit() return jsonify(book.to_dict())
def test_update_book_name(self, patched_query, patched_session): name = 'new_name' isbn = 'fake_isbn' author = 'fake_author' Book.add_book(name, 50, isbn, author) Book.update_book_name(isbn, name) patched_session.commit.assert_called() patched_query.filter_by.assert_called_once()
def test_add_book(self, patched_session): mock_book = self.mock_books[0] Book.add_book(_name=mock_book['name'], _isbn=mock_book['isbn'], _price=mock_book['price'], _author=mock_book['author']) patched_session.add.assert_called_once() patched_session.commit.assert_called_once()
def handle(self, *args, **options): data = pickle.load(open(str(args[0]))) Section.objects.all().delete() Book.objects.all().delete() i = 0 for quarter in data: for dept in quarter['departments']: for courses in dept['courses']: newCourseName = courses['name'] for section in courses['sections']: newSectionName = section['name'] newSectionID = section['id'] for book in section['books']: newISBN = book['ISBN'] newAuthor = book['author'] newBinding = book['binding'] newPrice = book['broncoListPrice'] newEdition = book['edition'] newRequired = book['isRequired'] newtitle = book['title'] newBook = Book( isbn = newISBN, sectionID = newSectionID, required = newRequired, broncoPrice = newPrice, author = newAuthor, edition = newEdition, binding = newBinding, title = newtitle ) newBook.save() print i i +=1 for quarter in data: for dept in quarter['departments']: for courses in dept['courses']: newCourseName = courses['name'] for section in courses['sections']: newSectionID = section['id'] newSectionName = section['name'] newInstructor = section['instructor'] newQuartername = quarter['name'] newCourse = Section( quarterName = newQuartername, courseName = newCourseName, sectionID = newSectionID, sectionName = newSectionName, instructor = newInstructor) newCourse.save() print newCourse
def test_adding_books(self): b1 = Book(metabook_id=1, owner_id=1, condition="new", region="sf") b2 = Book(metabook_id=1, owner_id=1, condition="used", region="hyd") b3 = Book(metabook_id=1, owner_id=1, condition="torn", region="sel") db.session.add_all([b1, b2, b3]) db.session.commit() hydbook = Book.query.filter_by(region="hyd").first() numbertorn = Book.query.filter_by(condition="torn").all() self.assertEqual(hydbook.owner_id, 1) self.assertEqual(len(numbertorn), 1)
def add_book(): form = BookForm() if form.validate_on_submit(): book = Book() book.book = form.name.data db.session.add(book) db.session.commit() flash("Book create with successfully!", "success") return redirect(url_for(".add_book")) return render_template("add.html", form=form)
def test_book_is_related_to_list_of_books(self): list_of_books = ListfOfBooks.objects.create() book = Book( list_of_books=list_of_books, title='Some title', current_page=1, total_pages=255, ) book.save() self.assertIn(book, list_of_books.book_set.all())
def test_update_book_price(self, patched_query, patched_session): # An alternative approach: test very lightly since the function is simple, just make sure the function # does not crash and commit is called once successfully isbn = 'fake_isbn' Book.update_book_price(isbn, 50) patched_query.filter_by.assert_called_once() patched_session.commit.assert_called_once()
def replace_book(isbn): if not valid_put_request_data(request.json): abort( 400, "Invalid book object passed in request. Data should be passed in similar to this {'name': " "'bookname', 'price': 7.99 }") Book.replace_book(isbn, request.json.get('name'), request.json.get('price')) return jsonify(dict()), 204
def test_cannot_save_empty_book_details(self): list_of_books = ListfOfBooks.objects.create() book = Book() book.title = "" # empty book detail (title) book.current_page = 6 book.total_pages = 344 book.list_of_books = list_of_books with self.assertRaises(ValidationError): book.save() book.full_clean() # fully checks empty value in TextField.
def add_book(title, author, description, pages_no): """Helper function for adding example book to db.""" book = Book(title=title, author=author, description=description, pages_no=pages_no) book.add_date() db.session.add(book) db.session.commit() return book
def add_book(): if not valid_book_object(request.json): abort( 400, "Invalid book object passed in request. Data passed in similar to this {'name': 'bookname', " "'price': 7.99, 'isbn': 9780394800165, 'author': 'Someone' }") Book.add_book(request.json.get('name'), request.json.get('price'), request.json.get('isbn'), request.json.get('author')) data = dict( Location=url_for('v1.get_book_by_isbn', isbn=request.json.get('isbn'))) return jsonify(data), 201
def test_adding_uploader(self): """Tests if an uploader can be added to a book.""" user = self.add_user() file = '/tmp/some-test-book.pdf' book = Book(title='book', publish_date=date.today(), file=file, file_type='pdf') book.uploader = user self.add_to_db(book) book = Book.query.all()[0] self.assertEqual(book.uploader, user)
def test_delete_book(self, patched_query, patched_session): mock_filter_by = Mock() patched_query.filter_by.return_value = mock_filter_by mock_filter_by.delete.return_value = True isbn = 'fake_isbn' Book.delete_book(isbn) patched_query.filter_by.assert_called_with(isbn=isbn) mock_filter_by.delete.assert_called_once() patched_session.commit.assert_called_once()
def update_book(isbn): if not valid_patch_request_data(request.json): abort( 400, "Invalid book object passed in request. Data should be passed in similar to this {'name': " "'bookname', 'price': 7.99 }") Book.update(isbn, **request.json) return jsonify( dict(Location=url_for('v1.get_book_by_isbn', isbn=isbn))), 204
def book_add(): form = BookForm() if form.validate_on_submit(): book = Book() book.name = form.name.data db.session.add(book) db.session.commit() flash("Livro cadastrado com sucesso", "success") return redirect(url_for('book.book_add')) return render_template('book/add.html', form=form)
def fill_books(books): for author in set([a for a in books.values()]): a = Author(name=author) db.session.add(a) db.session.commit() for book_name in books.keys(): b = Book(name=book_name) b.authors = [Author.query.filter_by(name=books[book_name]).first()] db.session.add(a) db.session.commit()
def add_book(): form = BookForm() form.author.choices = [(i.id, i.name) for i in Author.query.all()] if form.validate_on_submit(): Book.save(name=form.name.data, date=form.date.data, author_id=form.author.data) return redirect(url_for('books')) return render_template('form.html', title="Добавление новой книги", form=form, url=url_for('add_book'))
def test_adding_language_to_book(self): """Tests setting a language for a book.""" file = '/tmp/some-test-book.pdf' book = Book(title='book', publish_date=date.today(), file=file, file_type='pdf') lang = self.add_language() book.language = lang self.add_to_db(book) book = Book.query.all()[0] self.assertEqual(book.language, lang)
def setUp(self): from app.models import Book self.admin = User.objects.create_superuser( username='******', email='*****@*****.**', password='******' ) self.book1 = Book(pk=1, title="foo", body="foofoofoo", author=self.admin) self.book1.save() self.book2 = Book(pk=2, title="bar", body="barbarbar", author=self.admin) self.book2.save() # Delete TaggedItem everytime TaggedItem.objects.all().delete()
def deploy(): """Run deployment tasks.""" from flask.ext.migrate import upgrade from app.models import Role, User, Year, Book, Author from app import db db.drop_all() db.create_all() Role.insert_roles() User.generate_fake() Year.generate_fake() Author.generate_fake() Book.generate_fake()
def book_add(): form = LoginForm() book_form = BookForm(request.form) book_form.authors.choices = [(p.id, p.name) for p in db_session.query(Author).order_by('id')] if book_form.validate_on_submit(): book = Book() book.title = book_form.title.data book.authors = [db_session.query(Author).get(o) for o in book_form.authors.data] db_session.add(book) db_session.commit() flash('Successfully added.', 'success') return redirect(url_for('index')) return render_template("add_book.html", bform=book_form, form=form, user=current_user, is_authenticated=True)
def update_books(): title = request.form['title'] authors = request.form['authors'] data = json.loads(authors) book_id = request.form['id'] if book_id == 'new_book': book = Book(title) else: book = Book.get_byId(book_id, g.dbs) del book.authors[:] book.title = title for it in data: book.authors.append(Author.get_byId(it, g.dbs)) g.dbs.add(book) g.dbs.commit() return 'success'
def authors_of_book(): book_id = request.args['id'] book = Book.get_byId(book_id, g.dbs) author_ids = [] for author in book.authors: author_ids.append(author.id) json = dict(id=book_id) return jsonify(book_id=book.id, book_title=book.title, author_ids=author_ids)
def new_book(): form = NewBookForm() if form.validate_on_submit(): if form.book_title.data is None: flash("Fill in a book title to create a book!") return redirect(url_for('show_books')) book = Book(book_title=form.book_title.data) author = form.author.data book.authors.append(author) book.user = g.user if book.book_title in db.session.query(Book.book_title).all(): flash('This book title already exists.') return redirect(url_for('new_book')) db.session.add(book) db.session.commit() flash('Book successfully added.') return redirect(url_for('show_books')) return render_template('newbook.html', form=form)
def search_books(): form = SearchForm() results = None if request.method == 'POST' and form.validate_on_submit(): book = request.form['book'] author = request.form['author'] results = Book.get_byTitleAuthor(book, author, g.dbs) # flash('book: %s author: %s' % (books, author)) return render_template('search_books.html', form=form, results=results)
def delete_instance(): instance_type = request.form['type'] id = request.form['id'] if instance_type == 'book': instance = Book.get_byId(id, g.dbs) elif instance_type == 'author': instance = Author.get_byId(id, g.dbs) else: return 'wtf?' g.dbs.delete(instance) g.dbs.commit() return 'ok'
def new_entry(request): if request.session['user'] == 'admin': if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): cd = form.cleaned_data print(cd) post = Book(title=cd['title'], about=cd['about'], timestamp=cd['timestamp']) post.save() return HttpResponseRedirect('/books.html') else: ctx = Context({'form': form}) ctx.update(csrf(request)) return render_to_response('app/book_form.html', ctx) else: form = BookForm() ctx = Context({'form': form}) ctx.update(csrf(request)) return render_to_response('app/book_form.html', ctx) else: return render_to_response('app/index.html');
def get_added_books(delta_entries, user_id, client): """ Return a list of Books. All books in this list have the correct mimetype, are under the size limit, and don't have a duplicate hash in the database (i.e. not a filepath rename). """ added_entries = [] for entry in delta_entries: pathname, metadata = entry pathname = canonicalize(pathname) # First check that it's not a removed pathname. if metadata is None: continue # Check that pathname is a file, has an okay mimetype and is under the # size limit. if (metadata['is_dir'] or not mimetypes_filter(pathname) or metadata['bytes'] > AMAZON_SIZE_LIMIT): continue book = Book(user_id, pathname, metadata['bytes']) download_book(client, book, u'kindlebox') # Make sure that the book is not a duplicate of a previously added book # (probably a renamed file). duplicate = (Book.query.filter_by(user_id=user_id) .filter_by(book_hash=book.book_hash).first()) if (duplicate is not None): book.unsent = duplicate.unsent added_entries.append(book) return added_entries
def edit_books_and_authors(): books = Book.get_all(g.dbs) authors = Author.get_all(g.dbs) book_form = EditForm() author_form = AddAuthorForm() return render_template('edit_books_and_authors.html', books=books, authors=authors, form=book_form, author_form=author_form)
def ca(): db.create_all() Role.insert_roles() User.generate_fake() Book.generate_fake()
class TaggedItemTestCase(AppTestCase): installed_apps = ['universaltag.tests.app'] def setUp(self): from app.models import Book self.admin = User.objects.create_superuser( username='******', email='*****@*****.**', password='******' ) self.book1 = Book(pk=1, title="foo", body="foofoofoo", author=self.admin) self.book1.save() self.book2 = Book(pk=2, title="bar", body="barbarbar", author=self.admin) self.book2.save() # Delete TaggedItem everytime TaggedItem.objects.all().delete() def test_add_or_get(self): TaggedItem.objects.add_or_get(self.book1, 'test1') TaggedItem.objects.add_or_get(self.book1, 'test2') TaggedItem.objects.add_or_get(self.book1, 'test3') self.assertEquals(len(self.book1.tags.values()), 3) def test_add_or_get_duplicate(self): TaggedItem.objects.add_or_get(self.book1, 'test1') TaggedItem.objects.add_or_get(self.book1, 'test2') TaggedItem.objects.add_or_get(self.book1, 'test3') # Add duplicate tag TaggedItem.objects.add_or_get(self.book1, 'test3') self.assertEquals(len(self.book1.tags.values()), 3) def test_get_for_model(self): from app.models import Book TaggedItem.objects.add_or_get(self.book1, 'test1') TaggedItem.objects.add_or_get(self.book1, 'test2') TaggedItem.objects.add_or_get(self.book1, 'test3') TaggedItem.objects.add_or_get(self.book2, 'test2') TaggedItem.objects.add_or_get(self.book2, 'test3') TaggedItem.objects.add_or_get(self.book2, 'test4') qs = TaggedItem.objects.get_for_model(Book) self.assertEquals(qs.count(), 6) def test_get_for_object(self): TaggedItem.objects.add_or_get(self.book1, 'test1') TaggedItem.objects.add_or_get(self.book1, 'test2') TaggedItem.objects.add_or_get(self.book1, 'test3') TaggedItem.objects.add_or_get(self.book2, 'test2') TaggedItem.objects.add_or_get(self.book2, 'test3') TaggedItem.objects.add_or_get(self.book2, 'test4') qs = TaggedItem.objects.get_for_object(self.book1) self.assertEquals(qs.count(), 3) def test_remove(self): TaggedItem.objects.add_or_get(self.book1, 'test1') TaggedItem.objects.add_or_get(self.book1, 'test2') TaggedItem.objects.add_or_get(self.book1, 'test3') qs = TaggedItem.objects.get_for_object(self.book1) self.assertEquals(qs.count(), 3) TaggedItem.objects.remove(self.book1, 'test1') qs = TaggedItem.objects.get_for_object(self.book1) self.assertEquals(qs.count(), 2) def test_freeze(self): TaggedItem.objects.add_or_get(self.book1, 'test1') TaggedItem.objects.add_or_get(self.book1, 'test2') TaggedItem.objects.add_or_get(self.book1, 'test3') TaggedItem.objects.freeze(self.book1, 'test1', 'thaw') tagged_item = TaggedItem.objects.get_for_object(self.book1).get(tag__label='test1') self.assertFalse(tagged_item.frozen) TaggedItem.objects.freeze(self.book1, 'test1') tagged_item = TaggedItem.objects.get_for_object(self.book1).get(tag__label='test1') self.assertTrue(tagged_item.frozen) TaggedItem.objects.freeze(self.book1, 'test1') tagged_item = TaggedItem.objects.get_for_object(self.book1).get(tag__label='test1') self.assertFalse(tagged_item.frozen) def test_remove_fail(self): TaggedItem.objects.add_or_get(self.book1, 'test1') TaggedItem.objects.add_or_get(self.book1, 'test2') TaggedItem.objects.add_or_get(self.book1, 'test3') TaggedItem.objects.freeze(self.book1, 'test1', 'freeze') TaggedItem.objects.remove(self.book1, 'test1') qs = TaggedItem.objects.get_for_object(self.book1) self.assertEquals(qs.count(), 3) TaggedItem.objects.freeze(self.book1, 'test1', 'thaw') TaggedItem.objects.remove(self.book1, 'test1') qs = TaggedItem.objects.get_for_object(self.book1) self.assertEquals(qs.count(), 2) def test_reconstruct(self): TaggedItem.objects.add_or_get(self.book1, 'test1') TaggedItem.objects.add_or_get(self.book1, 'test2') TaggedItem.objects.add_or_get(self.book1, 'test3') NEW_TAGS = ("foobar1", "foobar2", "foobar3", "foobar4") TaggedItem.objects.reconstruct(self.book1, ",".join(NEW_TAGS)) qs = TaggedItem.objects.get_for_object(self.book1) for i, tagged_item in enumerate(qs): self.assertEquals(tagged_item.tag.label, NEW_TAGS[i])
def library(request): bookset = [] bookinformation = [] authorinformation = [] ALLset = Book.objects.all() if request.GET: post = request.GET if post.has_key('insertorupdate'):#insert or update new_book = Book( ISBN = post["ISBN"], Title=post['Title'], AuthorID = post["AuthorID"], Publisher = post["Publisher"], PublishDate = post["PublishDate"], Price = post['Price']) dset = Book.objects.filter(ISBN = post['ISBN']) if len(dset) != 0: #delete the repetitive book dset[0].delete() new_book.save() dset = Author.objects.filter(AuthorID = post['AuthorID']) if len(dset) == 0: # add an author new_author = Author( AuthorID = post['AuthorID'], Name = post['AuthorName'], Age = post['AuthorAge'], Country = post['AuthorCountry']) new_author.save() if post.has_key('delete'): #delete the book dset = Book.objects.filter(ISBN = post['ISBN']) if len(dset) != 0: aset = Book.objects.filter(AuthorID = dset[0].AuthorID) if len(aset) == 1: bset = Author.objects.filter(AuthorID = dset[0].AuthorID) bset[0].delete() #delete the author dset[0].delete() for i in ALLset: if post.has_key(i.Title):#show information of a book oneq = [] oneq.append(i) bookinformation = [] + oneq authorinformation = Author.objects.filter(AuthorID = i.AuthorID) break if post.has_key(i.ISBN): #delete the book aset = Book.objects.filter(AuthorID = i.AuthorID) if len(aset) == 1: bset = Author.objects.filter(AuthorID = i.AuthorID) bset[0].delete() #delete the author i.delete() break if post.has_key('toselect'):#search authorset = Author.objects.filter(Name = post['authorselect']) if len(authorset) != 0: bookset = Book.objects.filter(AuthorID = authorset[0].AuthorID) ALLset = Book.objects.all() return render_to_response('Book.html', {'ALLset': ALLset, 'ONE': bookinformation, \ 'AUTHOR': authorinformation, 'Bookset': bookset}, context_instance=RequestContext(request))