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 load_authors(): author1 = Author(name='qingfeng-27', email='*****@*****.**') author1.save() author2 = Author(name='mjiang', email='*****@*****.**') author2.save() authors = [] authors.append(author1) authors.append(author2) return authors
def create_paper(self, title, abstract, collaborators): new_paper = Paper(title=title, abstract=abstract, status=0) for collaborator in collaborators: author = Author() author.user = User.query.get(int(collaborator)) new_paper.authors.append(author) if not collaborators: author = Author() author.user = User.query.get(session['user_id']) new_paper.authors.append(author) db.session.add(new_paper) db.session.commit()
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 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 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 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 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_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 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 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 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 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 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 registration(): if request.method == "POST": form = request.form username = form.get("username") email = form.get("email") password = form.get("password") confirm_password = form.get("confirm_password") if username == None or email == None or password == None or confirm_password == None: error = "Username, email and passwords are required" return render_template("register.html", error=error) if " " in username: error = "Username should not have a space" return render_template("register.html", error=error) if " " in email: error = "Email address should not have a space" return render_template("register.html", error=error) if password != confirm_password: error = "Passwords do not match" return render_template("register.html", error=error) else: author = Author.query.filter_by(username=username).first() if author != None: error = "User with that username exists" return render_template("register.html", error=error) author = Author.query.filter_by(email=email).first() if author != None: error = "User with that email address exists" return render_template("register.html", error=error) author = Author(username=username, email=email) author.set_password(password) author.save_author() return redirect(url_for("auth.loginauthor")) return render_template("register.html")
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_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 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 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_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 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_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 test_add_book_to_author(self): """Tests if it is possible to add a book to an author.""" author = Author(name='Some Author') book = self.add_book() author.books.append(book) self.add_to_db(author) author = Author.query.all()[0] self.assertEqual(author.books[0], book)
def edit_upload_metadata(file): form = BookMetaDataForm() tmp_path = os.path.join(current_app.config['TMP_FOLDER'], file) form.language.choices = [(l.code, l.to_name(l.code)) for l in Language.query.all()] form.file_type.choices = [(ft, ft) for ft in current_app.config['FILE_TYPES']] if form.validate_on_submit(): filename = (form.title.data + '.' + form.file_type.data).\ replace(' ', '_') new_path = os.path.join(current_app.config['FILE_FOLDER'], filename) if not os.path.exists(current_app.config['FILE_FOLDER']): os.mkdir(current_app.config['FILE_FOLDER']) copyfile(tmp_path, new_path) os.remove(tmp_path) book = Book(title=form.title.data, file_type=form.file_type.data, file=new_path) if form.publish_date.data: book.publish_date = form.publish_date.data lang = Language.query.filter_by(code=form.language.data).first() if lang: book.language = lang book.set_hash() book.uploader = current_user author_names = form.authors.data.split(';') for author_name in author_names: author_name = author_name.strip() author = Author.query.filter_by(name=author_name).first() if not author: author = Author(name=author_name) db.session.add(author) db.session.commit() book.authors.append(author) db.session.add(book) db.session.commit() flash(f'Uploaded {book.title}') return redirect(url_for('books.details', id=book.id)) else: metadata = get_meta_data(tmp_path) form.title.data = metadata['title'] form.authors.data = metadata['authors'] form.language.data = metadata['language'] form.file_type.data = metadata['file_type'] form.publish_date.data = datetime.strptime(metadata['publish_date'], '%Y-%m-%d') return render_template('books/edit_metadata.html', form=form, title='Edit Meta Data')
def test_modelmixin(): assert Author.getone(1).author == 'Mucong Ding' assert len(Author.gets(pid=1)) == 2 assert Author.getpage(nums=2).has_next == True a = Author(pid=2, author="Foo Bar Go", authorrank=10) a.save(True) assert Author.get(authorrank=10).pid == 2 a.update(pid=3) assert Author.get(authorrank=10).pid == 3 assert a.dict() == {'author': 'Foo Bar Go', 'authorrank': 10, 'id': 27, 'pid': 3}
def add_author(): print('in author') name = request.form['name'] print(name) if not name: print('error') abort(400, "Author requires name.") auth = Author(name) print(auth) return redirect('/')
def test_relation_user_author_paper(self): author = Author() user = User() paper = Paper() user.authors.append(author) paper.authors.append(author) self.assertEqual(paper, user.authors[0].paper) self.assertEqual(user, paper.authors[0].user)
def post(self): """ Adding new book :return: Response """ form = BookForm() if form.validate_on_submit(): author = Author(escape(form.data["name"])) db.session.add(author) db.session.commit()
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) + '"}'