def authorInsertQuery(request): #if not request.user.is_authenticated or request.user.username != 'admin': # return redirect('/login') # if POST request, process form data if request.method == 'POST': # create form instance and pass data to ir form = AuthorInsertForm(request.POST) if form.is_valid(): # is it valid? name = form.cleaned_data['name'] email = form.cleaned_data['email'] aut = Author.objects.filter(email__icontains=email) if not aut: author = Author(name=name, email=email) author.save() return render(request, 'authorInserted.html', { 'aut': author, 'query': name }) else: return render(request, 'authorInsertv2.html', { 'error': False, 'exists': True }) # if GET (or any other method), create blank form else: form = AuthorInsertForm() return render(request, 'authorInsertv2.html', {'form': form})
def authorInsert(request): if not request.user.is_authenticated or request.user.username != 'admin': return redirect('/login') if 'email' in request.POST: query = request.POST if query: aut = Author.objects.filter(email__icontains=query['email']) if not aut: author = Author(name=query['name'], email=query['email']) author.save() return render(request, 'authorInserted.html', { 'aut': author, 'query': query['name'] }) else: return render(request, 'authorInsert.html', { 'error': False, 'exists': True }) else: return render(request, 'authorInsert.html', { 'error': True, 'exists': False }) else: return render(request, 'authorInsert.html', { 'error': False, 'exists': False })
def test_book_model(self): """ Test adding a book & number of records in Book table. """ author = Author(full_name="Erenest Hemingway") additional_author = Author(full_name="My Name") category = Category(category_name="War novel") additional_category = Category(category_name="WWII") book = Book( title="For Whom the Bell Toll", description="It tells the story of Robert Jordan.", book_categories=[category], book_authors=[author], ) db.session.add(book) db.session.commit() book.book_authors.append(additional_author) book.book_categories.append(additional_category) db.session.commit() self.assertEqual(Book.query.count(), 1) self.assertEqual(Book.query.first().title, "For Whom the Bell Toll") self.assertEqual(Book.query.first().description, "It tells the story of Robert Jordan.") self.assertEqual(Book.query.first().book_categories, [category, additional_category]) self.assertEqual(Book.query.first().book_authors, [author, additional_author])
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 generate_fakes(): Author.generate_fake() BookDetails.generate_fake() BookInventory.generate_fake() Client.generate_fake() Person.generate_fake() Volunteer.generate_fake() Donor.generate_fake()
def init_db(): current_app.logger.info('Database initilize begin...') db.drop_all() db.create_all() Author.init() Article.init() Constant.init() current_app.logger.info('initialize database done!')
def create_author(): author_info = request.json or request.form author = Author(name=author_info.get('name')) db.session.add(author) db.session.commit() return jsonify(author.to_dict())
def add_authors(): form = AuthorForm() if form.validate_on_submit(): Author.save(name=form.name.data) return redirect(url_for('authors')) return render_template('form.html', title="Добавление нового автора", form=form, url=url_for('add_authors'))
def _add_author(): json = request.get_json(force=True) name = json['name'] author = Author() author.author_name = name db.session.add(author) db.session.flush() new_id = author.author_id db.session.commit() return '{"new_id":"' + str(new_id) + '"}'
def update_authors(): author_id = request.form['active_author_id'] author_name = request.form['author_name'] if author_id == 'new_author': author = Author(author_name) else: author = Author.get_byId(author_id, g.dbs) author.name = author_name g.dbs.add(author) g.dbs.commit() return redirect(url_for('edit_books_and_authors'))
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 addauthor(request): if request.method == 'POST': form = AddAuthorForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] new_author = Author(name=name, email=email) new_author.save() return render(request, 'all_authors.html', {'authors': Author.objects.all()}) else: form = AddAuthorForm() return render(request, 'addauthor.html', {'form': form})
def create_author(): data = request.get_json() or {} if 'name' not in data: return bad_request('must include name') if Author.query.filter_by(name=data['name']).first(): return bad_request('please use a different name') author = Author() author.from_dict(data) db.session.add(author) db.session.commit() response = jsonify(author.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_author', id=author.id) return response
def author_add(): form = LoginForm() author_form = AuthorForm(request.form) author_form.books.choices = [(p.id, p.title) for p in db_session.query(Book).order_by('id')] if author_form.validate_on_submit(): author = Author() author.name = author_form.name.data author.books = [db_session.query(Book).get(o) for o in author_form.books.data] db_session.add(author) db_session.commit() flash('Successfully added.', 'success') return redirect(url_for('index')) return render_template("add_author.html", bform=author_form, form=form, user=current_user, is_authenticated=True)
def test_author_model(self) : author = Author(name='KJsa', email='*****@*****.**', screenname='kod', about='What up?', password='******') db.session.add(author) db.session.commit() assert author in db.session
def test_author_change_email(self) : auth_1 = Author(name='KJsa', email='*****@*****.**', screenname='kod', about='What up?', password='******') db.session.add(auth_1) db.session.commit() login_author(self.client, email='*****@*****.**', password='******') response = self.client.get(url_for('author.author_change_email', id=auth_1.id), follow_redirects=False) self.assertEqual(response.status_code, 200) response_1 = self.client.post('/author_change_email/1', data=dict(email='*****@*****.**'), follow_redirects=True) auth = Author.query.filter_by(name='KJsa').first() self.assertEqual(response_1.status_code, 200) self.assertEqual(response_1.status_code, 200) self.assertEqual(auth.email, '*****@*****.**') self.assertEqual(auth.password, 'pbkdf2:sha256:150000$73fMtgAp$1a1d8be4973cb2676c5f17275c43dc08583c8e450c94a282f9c443d34f72464c') self.assertEqual(auth.screenname, 'kod') logout_author(self.client)
def new_author(): form = NewAuthorForm() if form.validate_on_submit(): if form.name.data is None: flash("Fill in a author`s name to create an author!") return redirect(url_for('show_authors')) author = Author(name=form.name.data) author.user = g.user if author.name in db.session.query(Author.name).all(): flash('This author already exists.') return redirect(url_for('new_author')) db.session.add(author) db.session.commit() flash('Author successfully added.') return redirect(url_for('show_authors')) return render_template('author_new.html', form=form)
def authors_list(): form = AuthorForm() authors = Author.query.all() authors_names = [author.name for author in authors] error = None if request.method == "POST": # add new author if form.name.data not in authors_names: name = form.data['name'] author = Author(name=name) db.session.add(author) db.session.commit() else: # Proviso for existing string: error = "Taki autor już istnieje w bazie. " \ "Dodaj do nazwiska np. datę urodzenia " \ "lub inicjał, aby ich odróżnić" return render_template("authors.html", authors=authors, form=form, error=error) return redirect(url_for("authors_list")) return render_template("authors.html", authors=authors, form=form, error=error)
def test_write_paper(self): paper = Paper( title="How to conquer the World", abstract="just conquer it!", status=0 ) review = Review() author = Author() user_that_authored = User() user_that_reviews = User() user_that_authored.authors.append(author) user_that_reviews.reviews.append(review) paper.authors.append(author) paper.reviews.append(review) db.session.add(paper) db.session.commit() paper = Paper.query.all()[0] self.assertEqual(review, paper.reviews[0]) self.assertEqual(author, paper.authors[0]) self.assertEqual(user_that_authored, paper.authors[0].user) self.assertEqual(user_that_reviews, paper.reviews[0].user)
def test_relation_user_author(self): author = Author() user = User() user.authors.append(author) self.assertEqual(author, user.authors[0]) self.assertEqual(user, author.user)
def get(self, id): load_options = subqueryload(Author.books) author = Author.find_or_fail(id, load_options=load_options) data = author.json() data['books'] = [book.json() for book in author.books] return data
def book_edit(id): book = Book.query.filter_by(id=id).first() author = Author.query.filter_by(id=book.author_id).first() rental = Rental.query.filter_by(id=book.rental_id).first() form = BookForm(data={ 'tittle': book.tittle, 'author': author.name, 'quantity': book.quantity, 'status': rental.status, 'csrf_token': 1234}) if request.method == "POST": if form.validate_on_submit(): all_authors_names = [] all_authors_results = Author.query.all() for author in all_authors_results: all_authors_names.append(author.name) if form.data["author"] in all_authors_names: pass else: new_author = Author(name=form.data["author"]) db.session.add(new_author) db.session.commit() author_from_form = Author.query.filter_by(name=form.data['author']).first() rental_from_form = Rental.query.filter_by(status=form.data['status']).first() book.tittle = form.data["tittle"] book.quantity = form.data['quantity'] book.author_id = author_from_form.id book.rental_id = rental_from_form.id db.session.commit() return redirect((url_for("book_list"))) return render_template("book_id.html", form=form, id=id, book=book)
def create(request): if request.method == "GET": form = AuthorForm() return render(request, 'Library/author.html', {"form": form}) if request.method == "POST": form = AuthorForm(request.POST) if form.is_valid(): # process form data obj = Author(**form.cleaned_data) obj.save() return render(request, 'Library/author.html', {"form": AuthorForm(), "msg": {"status": "success", "msg": "Se añadio el author"} }) return render(request, 'Library/author.html', {"form": form})
def addbook(): form = AddBook() if form.validate_on_submit(): title = form.title.data author = form.author.data price = form.price.data pub_date = form.pub_date.data if title.lower() in [book.title.lower() for book in Book.query.all()]: flash('This book already exists in the store') return redirect('addbook') if author.lower() in [ auth.name.lower() for auth in Author.query.all() ]: author = Author.query.filter_by(name=author) else: author = Author(name=author) db.session.add(author) book = Book(title=title, author=author, price=price, pub_date=pub_date) db.session.add(book) db.session.commit() flash(f'{title} successfully added to the store') return redirect('index') return render_template('addbook.html', form=form)
def initAuthorsQuery(condition): authors = [] Author.objects.all().delete() for author in sorted(list(Article.objects.values_list('author', flat=True))): if author not in authors: wordsCount = {} for article in Article.objects.filter(author=author): wordsCount.update(wordCount(article.content)) wordsCount = { key: value for key, value in sorted( wordsCount.items(), key=lambda item: item[1], reverse=True) } wordsCount = json.dumps(dict(list(wordsCount.items())[0:10])) try: Author(author=author, words=wordsCount).save() except: Author.objects.all().delete() return False authors.append(author) return condition
def test_relation_author_paper(self): author = Author() paper = Paper() paper.authors.append(author) self.assertEqual(author, paper.authors[0]) self.assertEqual(paper, author.paper)
def new_article(): article_form = ArticleForm() author_subform = AuthorForm(prefix='authors-_-') if article_form.validate_on_submit(): article = Article( creation=date.today(), update=date.today(), title=article_form.title.data.lower(), link=article_form.link.data, year=article_form.year.data, journal=article_form.journal.data.lower() ) db.session.add(article) for author in article_form.authors.data: new_author = Author( creation=date.today(), update=date.today(), name=author['firstname'].lower(), surname=author['surname'].lower(), email=author['email'].lower() ) article.author.append(new_author) article.contributor.append(current_user) db.session.commit() article_id = article.id flash('Your Article Sheet has been submitted. Thank you!', 'success') return redirect(url_for('contribution.edit_policy_target', article_id=article_id)) return render_template('/edit_article.html', form=article_form, _template=author_subform )
def importBooks(): api1 = "https://www.googleapis.com/books/v1/volumes?q=" form = ImportBooks() global results if form.validate_on_submit() and form.submit.data: results = [] query = "+".join(form.keywords.data.split()) r = requests.get(api1 + query) jsonify = json.loads(r.content) #print(json.dumps(jsonify, indent=4, sort_keys=True)) for x in jsonify["items"]: results.append({"title": x["volumeInfo"]["title"]}) try: results[-1]["author"] = x["volumeInfo"]["authors"] except: results[-1]["author"] = "N/A" try: results[-1]["description"] = x["volumeInfo"]["description"] except: results[-1]["description"] = "N/A" try: results[-1]["genre"] = x["volumeInfo"]["categories"] except: results[-1]["genre"] = "N/A" print(results) if request.method == "POST" and form.move.data: print(results) for x in range(9): print(request.form.get(str(x))) data = request.form.getlist("checkbox") for x in data: flash(results[int(x)]["title"] + " - " + str(results[int(x)]["author"]) + " has been imported") author = Author.query.filter_by( name=results[int(x)]["author"][0]).first() if author is None: author = Author(name=results[int(x)]["author"][0]) db.session.add(author) db.session.commit() author_number = '' author = results[int(x)]["author"][0] authors = Author.query.all() print(author) for writer in authors: if author == writer.name: author_number = writer.id book = Book(title=results[int(x)]["title"], author_id=author_number, description=results[int(x)]["description"], genre=results[int(x)]["genre"][0]) db.session.add(book) db.session.commit() print("click") results = [] return render_template('import.html', title='Import Books', form=form, results=results)
def test_learner_login(self): w_cat = WorksheetCategory(name='dunk') db.session.add(w_cat) db.session.commit() auth_1 = Author( name='Kidkaid', email='*****@*****.**', password= '******' ) db.session.add(auth_1) db.session.commit() worksheet = Worksheet(pdf_url='tudoloos.pdf', name='tudoloos', author_id=1, author=auth_1, category_id=1, category=w_cat) db.session.add(worksheet) db.session.commit() worksheet_1 = Worksheet(pdf_url='tudol.pdf', name='tudol', author_id=1, author=auth_1, category_id=1, category=w_cat) db.session.add(worksheet_1) db.session.commit() learner = Learner( name='KJsa', email='*****@*****.**', screenname='kod', password= '******' ) learner.favourites.append(worksheet) learner.favourites.append(worksheet_1) db.session.add(learner) db.session.commit() with self.app.test_client() as c: response = c.post('/learner_login', data=dict(email='*****@*****.**', password='******'), follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertEqual(flask.session['learner_logged_in'], True) self.assertEqual(flask.session['learner_name'], 'KJsa') response_1 = c.get('/learner_logout', follow_redirects=True) self.assertEqual(response_1.status_code, 200) self.assertEqual(flask.session['learner_logged_in'], False)
def add_author(name, books=None): author = Author(name=name) if books: for book in books: author.books.append(book) db.session.add(author) db.session.commit() return author
def put(self, id): author = Author.find_or_fail(id) data = self.parser.parse_args() for key, value in data.items(): setattr(author, key, value) author.save() return author.json()
def merge_authors(self, paper, collaborators): def author_query(user_id): return (Author.query.filter_by(user_id=user_id, paper_id=paper.id).first()) new_author = (lambda: Author()) self.merge_generic(paper, collaborators, paper.authors, author_query, new_author)
def test_json_representation_of_author(): """ GIVEN a Author model WHEN a new Author is created THEN check the json representation of the new Author """ author_data = dict( first_name='John', last_name='Doe', gender='M', about='Lorem ipsum dolor sit amet.', ) author = Author(**author_data) author_json = author.json() assert_that(author_json).contains_value('John', 'Doe', 'M') assert_that(author_json).contains_key('first_name', 'last_name', 'gender', 'about')
def test_author_model(self): """ Test adding an author & count number of records in Author table. """ author = Author(full_name="Ernest Hemingway") db.session.add(author) db.session.commit() self.assertEqual(Author.query.first().full_name, "Ernest Hemingway") self.assertEqual(Author.query.count(), 1)
def addauthor(): form = AuthorForm(request.form) if request.method == 'POST' and form.validate(): user = Author(form.name.data, form.lastname.data, form.born.data) db.session.add(user) db.session.commit() return redirect(url_for('authors')) return render_template('addauthor.html', form=form)
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 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 init_books(): Author.generate_fake() BookDetails.generate_fake() BookInventory.generate_fake()
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))
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)