def create_poll(): form = CreatePollForm() if form.validate_on_submit(): new_poll = Poll(title=form.title.data, public=form.public.data, description=form.description.data) current_user.polls.append(new_poll) for question in form.questionList.data: if question['questionType'] == "sliderField": new_question = Question(question_title=question['questionTitle'], type="sliderField", lower_label=question['answerList'][0]['answer'], upper_label=question['answerList'][1]['answer']) new_poll.questions.append(new_question) for num in range(1, 11): new_answer = Answer(answer=num) new_question.answers.append(new_answer) else: new_question = Question(question_title=question['questionTitle'], type=question['questionType']) new_poll.questions.append(new_question) if question['questionType'] == "textField": new_answer = Answer(answer="text") new_question.answers.append(new_answer) for answer in question['answerList']: new_answer = Answer(answer=answer['answer']) new_question.answers.append(new_answer) db.session.commit() #poll_created_email(current_user, new_poll) return redirect(url_for('poll_preview', poll_id=new_poll.id)) return render_template('create_poll.html', form=form)
def createQuiz(): if current_user.is_admin == True: form = QuizCreation() if request.method == 'GET': return render_template('createQuizNew.html', title='Create Quiz', form=form) if form.validate_on_submit(): quiz = Quiz(quiz_name=form.quiz_name.data, quiz_details=form.quiz_details.data, date_posted=datetime.now()) db.session.add(quiz) db.session.commit() quiz = Quiz.query.filter_by(quiz_name = form.quiz_name.data).first() for question in form.question.data: new_question = Question(question=question["quizQuestion"], quiz=quiz.id) db.session.add(new_question) db.session.commit() id_question = Question.query.filter_by(question=question["quizQuestion"]).first() answers1 = Answer(answer=question["quizAnswer"], correct=True, questions=id_question.id, quiz=quiz.id) option1 = Answer(answer=question["option1"], correct=False, questions=id_question.id, quiz=quiz.id) option2 = Answer(answer=question["option2"], correct=False, questions=id_question.id, quiz=quiz.id) option3 = Answer(answer=question["option3"], correct=False, questions=id_question.id, quiz=quiz.id) db.session.add(answers1) db.session.add(option1) db.session.add(option2) db.session.add(option3) db.session.commit() return redirect(url_for('quizSelector')) else: return redirect(url_for('index'))
def save_answer(form, poll_id): for answer in form.select_entries.data: question = Question.query.filter_by(id=answer['question']).first() if current_user.is_active: submitted_answer = Answer(answerer=current_user, src_question=question, result=answer['option']) else: user = User.query.filter_by(username='******').first() if user is None: u = User(username='******') db.session.add(u) db.session.commit() user = User.query.filter_by(username='******').first() submitted_answer = Answer(answerer=user, src_question=question, result=answer['option']) db.session.add(submitted_answer) db.session.commit()
def addAnswer(): try: data = request.json if data is None: return response_error(MESSAGE.INVALID_PARAMETER, CODE.INVALID_PARAMETER) bm_id = data['bm_id'] questions = data['question'] user_id = get_jwt_identity() if len(questions) == 0: return response_error(MESSAGE.EMPTY_QUESTION, CODE.EMPTY_QUESTION) for q in questions: answer = Answer( bm_id=bm_id, answer=q['answer'], question_id=q['id'], user_id=user_id ) db.session.add(answer) db.session.commit() return response_ok() except Exception as ex: db.session.rollback() return response_error(str(ex))
def post_answer(question_id): _id = question_id.strip() validation = validate.validate_entered_id(_id) if validation: return validation data = request.get_json() answer = data.get("answer") ans = answer.strip() validation2 = validate.validate_input(ans) if validation2: return validation2 if any(dy["answer"] == ans for dy in all_answers): if any(xy["qstn_id"] == _id for xy in all_answers): return jsonify({"message": "Answer already exists"}), 409 for question in range(len(all_questions)): if ((all_questions[question]["qstn_id"]) == int(_id)): ans_id = len(all_answers) + 1 new_answer = Answer(ans_id, ans, _id) all_answers.append(new_answer) return jsonify({ "message": "Answer successfully posted to question", "Question answered": [all_questions[question]["question"]] }), 201 return jsonify({ "message": "No such question is available", }), 204
def index(): form = SurveyForm() if form.validate_on_submit(): voter = Voter(name=form.name.data, email=form.email.data) db.session.add(voter) db.session.commit() answer = Answer(age=form.age.data, gender=form.gender.data, path=form.path.data, voter=voter) db.session.add(answer) db.session.commit() for i in range(0, len(form.language.data)): language = Language(language=form.language.data[i], voter=voter) db.session.add(language) db.session.commit() comment = Comment(comment=form.text_area.data, voter=voter) db.session.add(comment) db.session.commit() flash(f"Thanks, the survey has been submitted!") return redirect(url_for('index')) return render_template('survey.html', form=form)
def answer(id): # Figure out if answer already exists question = Question.query.get(int(id)) answer = Answer.query.filter_by(question=question).first() form = AnswerForm() # If answer doesn't yet exist if answer is None: if form.validate_on_submit(): answer = Answer(body=form.body.data, author=current_user, question=question) db.session.add(answer) db.session.commit() flash(f'Your response has been recorded') return redirect(url_for('profile', username=current_user.username)) elif request.method == 'GET': form.body.data = answer.body # Validate an existing answer elif form.validate_on_submit(): answer.body = form.body.data db.session.commit() flash(f'Your response has been edited') return redirect(url_for('profile', username=current_user.username)) return render_template('answer.html', form=form, question=question, title='Answer')
def startQuiz(QuizsetID, current_question, time_limit): current_question = int(current_question) question_num = QuizSet.query.filter_by(id=QuizsetID).first().question_num teacher_id = QuizSet.query.filter_by(id=QuizsetID).first().author_id teacher_name = User.query.filter_by(id=teacher_id).first().name #calculate previous questions number prev_num = Prev_Questions_num(QuizsetID) form = QuizAnswerForm() if form.validate_on_submit(): answer = Answer(Answer=form.answer.data, question_id=prev_num + current_question, quizset_id=QuizsetID, student_id=current_user.id, marked=0) db.session.add(answer) db.session.commit() return redirect( url_for('answerSaved', current_question=current_question, QuizsetID=QuizsetID, time_limit=time_limit)) return render_template('startQuiz.html', prev_num=prev_num, QuizsetID=QuizsetID, current_question=current_question, Question=Question, teacher_name=teacher_name, question_num=question_num, form=form, time_limit=time_limit)
def fill_answers(self, n): print("filling ", n, " answers") questions = list(Question.objects.values_list("id", flat=True)) users = list(User.objects.values_list("id", flat=True)) answers = [] for i in range(n): answer = Answer(question_id=choice(questions), user_id=choice(users), text=". ".join(Faker().sentences( Faker().random_int(min=2, max=5))), date=Faker().date_between("-100d", "today"), is_correct=Faker().random.randint(0, 1)) answers.append(answer) batch_size = 100 n_batches = len(answers) if len(answers) % batch_size != 0: n_batches += 1 for i in range(n_batches): start = batch_size * i end = batch_size * (i + 1) Answer.objects.bulk_create(answers[start:end], batch_size)
def post_answer(): if request.method == 'POST': data = request.get_json() game_name = data['game_name'] typ = data['game_typ'] print(game_name, typ) del data['game_name'], data['game_typ'] game = Game.query.filter_by(name=game_name, typ=typ).first() if 'answer_id' in data: answer = Answer.query.filter_by(id=data['answer_id']).first() else: answer = Answer() answer.user_id = current_user.id if sess['session_id'] > 0 and 'attempt_id' in sess: t = Attempt.query.get(sess['attempt_id']) t.answers.append(answer) else: db.session.add(answer) answer.game_id = game.id for attr in data: setattr(answer, attr, data[attr]) db.session.commit() if 'progress' in sess: sess['progress'] += 1 return "" else: pass
def fill_answers(self, cnt): if cnt is None: return False print('Start filling {} answers'.format(cnt)) questions_id = list(Question.objects.values_list('id', flat=True)) authors_id = list(Profile.objects.values_list('id', flat=True)) authors_rand = choices(authors_id, k=cnt) objs = (Answer(question_id=choice(questions_id), author_id=authors_rand[i], text=f.text()) for i in range(cnt)) self.bulk_create(Answer, objs) print('End filling answers') print('Start updating {} authors'.format(len(authors_id))) authors_count = dict.fromkeys(authors_id, 0) for i in authors_rand: authors_count[i] += 1 authors = list(Profile.objects.all()) for author in authors: author.count = authors_count[author.pk] Profile.objects.bulk_update(authors, ['count']) print('End updating authors')
def save(self, commit=True): answer = Answer(text=self.cleaned_data.get('text')) answer.author = self.author answer.question = self.question if commit: answer.save() return answer
def create_question(cls, obj, taskType): """Метод генерирующий вопросы и ответы по типам задачи Arg: obj (TopicQuestion): Объекто вопроса taskType (str): Тип генерируемой задачи """ dict_of_types = { 1: QuestionTemplate.generate_question, 2: QuestionTemplate.generate_question_two, 4: QuestionTemplate.generate_question_four, 5: QuestionTemplate.generate_question_five, 6: QuestionTemplate.generate_question_six, 7: QuestionTemplate.generate_question_seven, 8: QuestionTemplate.generate_question_8, 9: QuestionTemplate.generate_question_9, 10: QuestionTemplate.generate_question_10, 11: QuestionTemplate.generate_question_11, 12: QuestionTemplate.generate_question_12, 13: QuestionTemplate.generate_question_13, 14: QuestionTemplate.generate_question_14, 15: QuestionTemplate.generate_question_15, 16: QuestionTemplate.generate_question_16 } generated_data = dict_of_types[taskType]() obj.text = generated_data['text'] answers = [] if 'variable_answers' in generated_data: for i in generated_data['variable_answers']: right = generated_data['truly_answer'] == i answers.append(Answer(text=i, right=right, question=obj)) Answer.objects.bulk_create(answers) obj.save()
def post_newTest(): # Является ли пользователь авторизованым if not current_user.is_authenticated: return json.dumps({'state': 3}), 200, { 'ContentType': 'application/json' } # Является ли пользователь администратором if Role.query.get(current_user.roleid).code != 1: return json.dumps({'state': 4}), 200, { 'ContentType': 'application/json' } if not request.json or not 'question' in request.json: return json.dumps({'error': 'incorrect_params'}), 400, { 'ContentType': 'application/json' } question = json.loads(request.json['question']) db.session.add(Question(text=question["text"], themeid=question["themeid"])) questionId = Question.query.all() questionId = questionId[len(questionId) - 1].id for element in question["answers"]: db.session.add( Answer(text=element["text"], iscorrect=element["iscorrect"], questionid=questionId)) db.session.commit() # Выполнено успешно return json.dumps({"state": 1}), 200, {'ContentType': 'application/json'}
def add_answer(): user = request.args.get('user') movie = request.args.get('movie') question = request.args.get('question') answer = request.args.get('answer') userid = User.query.filter_by(username=user).first().id movieid = Movie.query.filter_by(movie_title=movie).first().id questionid = Question.query.filter_by(movie_id=movieid, question_text=question).first().id check_answer = Answer.query.filter_by(user_id=userid, movie_id=movieid, question_id=questionid, answer_text=answer).first() if check_answer: pass else: new_answer = Answer(user_id=userid, movie_id=movieid, question_id=questionid, answer_text=answer) db.session.add(new_answer) db.session.commit() verify_answer = Answer.query.filter_by(user_id=userid, movie_id=movieid, question_id=questionid, answer_text=answer).first() return str(verify_answer.answer_text)
def create(question_id): question = Question.query.get_or_404(question_id) content = request.form['content'] answser = Answer(content=content, create_date=datetime.now()) question.answer_set.append(answer) db.session.commit() return redirect(url_for('question.detail', question_id=question_id))
def post(self, poll_id): poll = Poll.query.get_or_404(poll_id) parser = reqparse.RequestParser() parser.add_argument("user_login", type=str) parser.add_argument("answers", type=dict, action="append") answers = parser.parse_args() user = User.query.filter_by(login=answers.user_login).first() print(answers, user) for question in poll.questions: id_in_json = False for answer in answers.answers: if question.id == answer['question_id']: id_in_json = True new_answer = Answer(user=user, question=question) if question.type == 'variants': if question.multiple_answers: for option in answer['multiple_answers']: new_answer.selected_option.append(PossibleAnswer.query.get_or_404(option)) else: new_answer.selected_option.append(PossibleAnswer.query.get(answer['select_answer'])) else: new_answer.answer = answer['text_answer'] db.session.add(new_answer) break if not id_in_json: return f"question {question.id} does not exist", 400 db.session.commit() return 'OK', 200
def create(): form = QAForm() answer = Answer(text=form.text.data, question_id=form.question_id.data, up_votes=0, down_votes=0, total_votes=0, user_id=current_user.id) db.session.add(answer) db.session.commit() flash('Your answer was posted!') return redirect(url_for('questions.show', id=answer.question_id)) # redirect to the show view for the question of the newly created answer
def question(id): question = Question.query.get_or_404(id) form = AnswerForm() if form.validate_on_submit(): answer = Answer(body=form.body.data, question=question, author=current_user._get_current_object(), question_title=question.title) db.session.add(answer) db.session.commit() flash('回答成功!') return redirect(url_for('.question', id=question.id, page=-1)) #page=-1用来请求最后一页 page = request.args.get('page', 1, type=int) if page == -1: page = (question.answers.count() - 1) // current_app.config['FLASK_ANSWERS_PER_PAGE'] + 1 pagination = question.answers.order_by(Answer.timestamp.asc()).paginate( page, per_page=current_app.config['FLASK_ANSWERS_PER_PAGE'], error_out=False) #新答案显示在底部 answers = pagination.items return render_template('question.html', form=form, questions=[question], answers=answers, pagination=pagination)
def test_init(self): '''test that an answer is initialized''' self.new_answer = Answer(id=1, body="how to init python how to init python how to init python", question_id=1, user_id=1, date_created=datetime.now(), date_modified=datetime.now(), accept=False) self.assertTrue(type(self.new_answer.id), int) self.assertEqual(type(self.new_answer), Answer)
def answer(questionId): if request.method == "GET": question_id = questionId response = Answer.query.filter_by(questionId=question_id).order_by( Answer.voteCount.desc()).all() return {"answers": [answer.to_dict() for answer in response]} if request.method == "POST": data = request.get_json() userId = data['userId'] questionId = data['questionId'] body = data['body'] if not body: return jsonify(message="A body is required"), 400 voteCount = data['voteCount'] username = data['username'] answer = Answer(userId=userId, questionId=questionId, body=body, voteCount=voteCount, username=username) db.session.add(answer) db.session.commit() answer1 = answer.to_dict() return jsonify(answer=answer1), 200
def ask_question(): form = AskQuestionForm() # may need to be q and a form if form.validate_on_submit(): question = Question( body=form.question.data, title=form.question_title.data, author=current_user) db.session.add(question) db.session.commit() answer = Answer(date=datetime.utcnow(), user_id=question.user_id, body=form.answer.data, question_id=question.id) db.session.add(answer) db.session.commit() flash('Your question has been posted.') return redirect(url_for('ask_question')) # keep refresh from resubmitting post req return render_template( 'ask_question.html', title='Ask Question', form=form)
def setUp(self): #creates an virtual environment self.app = app.test_client() #make sure database is empty db.drop_all() db.create_all() a = Answer(Answer='This is my answer', marked=False) db.session.add(a) db.session.commit()
def generate_answers(self, cnt): for i in range(cnt): answer = Answer() answer.is_correct = choice([True, False]) answer.text = ' '.join(f.sentences(f.random_int(min=3, max=6))) answer.question_id = self.get_random_question_id() answer.user_id = self.get_random_user_id() answer.save()
def save_answer(dict, email): for k, v in dict.iteritems(): m = re.search(r"question(\d+)", k) if m: id = m.group(1) q = Question.query.get(id) a = Answer(description=v, question=q, email=email) db.session.add(a) db.session.commit()
def test_POST_request(): owner = None answers = { "answers": [{ "answer": { "questionId": 38, "answerValue": "True", "altQuestionId": 34 } }, { "answer": { "questionId": 34, "answerValue": "false", "altQuestionId": 38 } }], "metadata": [{ "key": "lang", "value": "DE" }, { "key": "country", "value": "Switzerland" }] } for answer in answers["answers"]: #create new answer if answer["answer"]["answerValue"] in ["true", "True", "TRUE", "1", 1]: ansValue = True else: ansValue = False new_answer = Answer(questionId=int(answer["answer"]["questionId"]), altQuestionId=int( answer["answer"]["altQuestionId"]), answerValue=answer["answer"]["answerValue"], source=owner) print("created answer") #save answer to db db.session.add(new_answer) db.session.commit() print("commited answer") for meta in answers["metadata"]: #create new meta data new_metadata = AnswerMeta(answerId=new_answer.id, key=meta["key"], value=meta["value"]) print("created meta") #save metadata db.session.add(new_metadata) db.session.commit() #save metadata print("commited meta")
def make_a_answer(self, body, question_id, user): question = Question.objects.get(pk=question_id) answer = Answer() answer.question = question answer.body = body answer.creator = user answer.updater = user answer.is_accepted = False answer.save() question.save() return answer
def deal_with_answer(request, question): form = AnswerForm(request.POST) print('arrive deal_with_answer') if form.is_valid(): answer = form.cleaned_data['answer'] c = Answer(answerer=request.user.profile, belong_to_question=question) c.content = answer c.save() return AnswerForm else: return form
def save(self, commit=True): answer = Answer(text=self.cleaned_data.get('text')) answer.profile = Profile.objects.get(user=self.user) question = self.question question.answer_count += 1 question.save() answer.question = question answer.is_correct = False if commit: answer.save() return answer
def dismiss_question(class_id, question_id): if request.method == 'POST': req_data = request.get_json() selected_question = Question.query.get(question_id) answer = Answer(content=req_data['answer'], instructor_id=req_data['instructor_id'], question_id=question_id, active=False) db.session.add(answer) selected_question.resolved = True db.session.add(selected_question) db.session.commit() return jsonify("QUESITON DISMISS TEST")