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 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 test_game_lottery2(self): u1 = User(nickname = 'john', email = '*****@*****.**',role = ROLE_RESEARCHER) u2 = User(nickname = 'john', email = '*****@*****.**') survey = Survey(title = "test",researcher = u1) s1 = Section (title = "1",description = "a",survey = survey) q1 = QuestionText(text="q1",section=s1) ans1 = Answer(user=u1,question=q1,answerText="1.5") ans2 = Answer(user=u2,question=q1,answerText="2.5") db.session.add(u1) db.session.add(u2) db.session.add(survey) db.session.add(s1) db.session.add(q1) db.session.add(ans1) db.session.add(ans2) game = GameLottery2(survey=survey, userA=u1,userB=u2,answerA=ans1,answerB=ans2) db.session.add(game) db.session.commit() self.assertEqual(game.moneyA,12.25) self.assertEqual(game.moneyB,13.75) ans1.answerText="0" ans2.answerText="0" db.session.add(ans1) db.session.add(ans2) game = GameLottery1(survey=survey, userA=u1,userB=u2,answerA=ans1,answerB=ans2) db.session.add(game) db.session.commit() self.assertEqual(game.percent_playerA,0) self.assertEqual(game.percent_playerB,0) self.assertEqual(game.moneyA,10) self.assertEqual(game.moneyB,10)
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 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 put(self, id, answer_id): '''Accept an answer and update an answer''' question = Question.get_by_id(id=id) logged_in_user = get_jwt_identity() answer_to_update = Answer.get_by_id(answer_id) print(answer_to_update) if question: if answer_to_update: if answer_to_update['user_id'] == logged_in_user: parser = reqparse.RequestParser() parser.add_argument('body', help='The body field cannot be blank', required=True, type=str) parser.parse_args() answer_to_update = Answer.update(id=answer_id, body=request.json['body'], user_id=get_jwt_identity(), accept=False) return {"message": "You have successfully updated the answer", "data": answer_to_update}, 201 if question['user']["id"] == logged_in_user and answer_to_update['question_id'] == question["id"]: if Validate.check_answer_accepted(question_id=question["id"]): return {"message": "The question has an already acceped answer"}, 405 Answer.accept(id=answer_id) return {"message": "You have successfully accepted the answer"}, 201 else: return {"message": "You are not authorized to modify the answer"}, 401 return {"message": "Answer not found"}, 404 return {"message": "No question found with that answer"}, 404
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 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 answer(question_id): form = answerForm() question_alias = Question.query.filter(Question.id==question_id).first().alias if form.validate_on_submit(): item = Answer() form.populate_obj(item) item.author = login.current_user.get_id() item.question = question_id db.session.add(item) db.session.commit() return redirect('/question/'+question_alias+'/')
def answer(poll_id): poll = Poll.query.get_or_404(poll_id) if current_user != poll.creator: if current_user not in poll.access_participation: if current_user in poll.access_results: return redirect(url_for('results', poll_id=poll_id)) else: return redirect(url_for('view_poll', poll_id=poll_id)) if poll.participation_in(current_user) and poll.repeat_type == 'false': if current_user in poll.access_results or current_user == poll.creator: return redirect(url_for('results', poll_id=poll_id)) else: return redirect(url_for('my_answers', poll_id=poll_id)) form = PollAnswerForm() if request.method == 'POST': for form_answer in form.answers: question = Question.query.get(form_answer.question_id.data) new_answer = Answer(user=current_user, question=question) if question.type == 'variants': if question.multiple_answers: for option in form_answer.multi_selected_option.data: new_answer.selected_option.append(PossibleAnswer.query.get(option)) else: new_answer.selected_option.append(PossibleAnswer.query.get(form_answer.selected_option.data)) else: new_answer.answer = form_answer.text_answer.data db.session.add(new_answer) db.session.commit() return redirect(url_for('index')) for question in poll.questions: answer_form = form.answers.append_entry() answer_form.question_id.data = question.id if question.type == 'variants': choices = [] for option in question.possible_answers: choices.append((option.id, option.option)) if question.multiple_answers: answer_form.kind.data = 'multiSelect' answer_form.multi_selected_option.choices = choices else: answer_form.kind.data = 'select' answer_form.selected_option.choices = choices else: answer_form.kind.data = 'text' answer_form.label = question.question return render_template('new_answer.html', form=form)
def query(self): id = g.uid row = User.Query().filter_by(id=id).first() has_answered = Answer.Query().filter_by(user_id=g.uid).count() has_incorrect = Answer.Query().filter_by(user_id=g.uid, is_right=False).count() user = { "id": row.id, "name": row.name, "phone": row.phone, "has_answered": has_answered, "has_incorrect": has_incorrect } return error.success(user)
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 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 deploy(): from app import db from app.models import User, Role, Question, Answer, Comment, Vote # db.drop_all() # db.create_all() # db.session.commit() Role.insert_roles() # #User.generate_fake() # User.add_self_follows() Question.generate_fake() Answer.generate_fake() # Comment.generate_fake() Vote.generate_fake()
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 query(self): pageNo = int( request.args.get("pageNo") or request.form.get("pageNo") or 1) pageSize = int( request.args.get("pageSize") or request.form.get("pageSize") or 10) query = Answer.Query() rows = query.offset((pageNo - 1) * pageSize).limit(pageSize).all() answers = [] for r in rows: user = User.Query().filter_by(id=r.user_id).first() question = Question.Query().filter_by(id=r.question_id).first() print(question.category_id) category = Category.Query().filter_by( id=question.category_id).first() answer = { "id": r.id, "username": user.name, "subject": question.subject, "category": category.name, "question_id": question.id, "question_content": question.content, "is_right": r.is_right, "user_answer": r.user_answer } answers.append(answer) return error.success({"list": answers})
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 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 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 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(): 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 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 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 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 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 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 check_answer_accepted(question_id): '''Method to check whether a question has an accepted answer''' answers = Answer.get_all_question_answers(question_id) for answer in answers: if answer['accept']: return True return False
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 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 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 create_answer(request, question_id): ans = Answer() ans.question = Question.objects.get(pk=question_id) ans.author = request.user ans.content = request.POST['content'] ans.is_better = False ans.save() return HttpResponseRedirect(reverse('question-details', args=(question_id,)))
def uploadQuestionFromPath(self, questionsPath): with open(questionsPath + u'/questions.txt') as questionsLoreFile: questions_list = json.loads(questionsLoreFile.read()) for q in questions_list: theme = db.session.query(Theme).filter(Theme.name == q['theme']).one() question_obj = Question(text=q['question'], theme=theme, image_name=q['image'] ) i = 1; for ans in q['answers']: answ = Answer(question_id=question_obj.id, text=ans) if i == q['correct_answer_index']: answ.is_correct = True else: answ.is_correct = False i += 1 db.session.add(answ) question_obj.answers.append(answ) db.session.add(question_obj) db.session.commit()
def new_answer(question,form,user): if isinstance (question,QuestionYN): answer = Answer (answerYN = (form["c"+str(question.id)].data=='Yes'), user= user, question = question) answer.answerText = str(answer.answerYN) if isinstance (question,QuestionText): if question.isNumber: if question.isNumberFloat: answer = Answer (answerNumeric = form["c"+str(question.id)].data.replace(",","."), user= user, question = question) else: answer = Answer (answerNumeric = form["c"+str(question.id)].data, user= user, question = question) answer.answerText= answer.answerNumeric else: answer = Answer (answerText = form["c"+str(question.id)].data, user= user, question = question) if isinstance (question,QuestionChoice): answer = Answer (answerNumeric = form["c"+str(question.id)].data, user= user, question = question) answer.answerText = form["c"+str(question.id)].choices[int(form["c"+str(question.id)].data)][1] if isinstance (question, QuestionLikertScale): answer = Answer (answerNumeric = form["c"+str(question.id)].data, user= user, question = question) answer.answerText = form["c"+str(question.id)].choices[int(form["c"+str(question.id)].data)][1] answer.globalTime = form["globalTimec"+str(question.id)].data answer.differentialTime = form["differentialTimec"+str(question.id)].data return answer
def answer_question(user,q, time): l=[0,0.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5,10] l2=[0,2,4,6,8,10,12,14,16,18,20] if q.decision=="decision_one_v1": i=random.choice(l) answer=models.Answer(answerNumeric=i,user=user,question=q) answer.answerText=(i) elif q.decision=="decision_one_v2": i=random.choice(l) answer=models.Answer(answerNumeric=i,user=user,question=q) answer.answerText=(i) elif q.decision=="decision_two": i=random.choice(l) answer=models.Answer(answerNumeric=i,user=user,question=q) answer.answerText=(i) elif q.decision=="decision_three": i=random.choice(l) answer=models.Answer(answerNumeric=i,user=user,question=q) answer.answerText=(i) elif q.decision=="decision_four": i=random.choice(l2) answer=models.Answer(answerNumeric=i,user=user,question=q) answer.answerText=(i) elif q.decision=="decision_six": i=random.choice(l2) answer=models.Answer(answerNumeric=i,user=user,question=q) answer.answerText=(i) elif q.decision=="decision_five": i=random.randrange(0,2) answer=models.Answer(answerNumeric=i,user=user,question=q) answer.answerText = q.choices[answer.answerNumeric] elif isinstance (q, QuestionYN): answer = Answer (answerYN =random.randrange(0,2)==1, user= user, question = q) answer.answerText = str(answer.answerYN) elif isinstance (q, QuestionText): if q.isExpectedAnswer(): if random.choice([0,1,1])==1: # 66% of know the answer answer = Answer (answerText =q.expectedAnswer.lower(), user= user, question = q) answer.numberAttempt= random.randrange(1, q.maxNumberAttempt+1) else: answer = Answer (answerText =forgery_py.forgery.lorem_ipsum.word(), user= user, question = q) answer.numberAttempt= q.maxNumberAttempt+1 elif q.isNumber: answer = Answer (answerNumeric =random.randrange(0,100), user= user, question = q) answer.answerText = answer.answerNumeric else: answer = Answer (answerText =forgery_py.forgery.lorem_ipsum.word(), user= user, question = q) elif isinstance (q,QuestionChoice): if q.is_range: answer = Answer (answerNumeric =random.randrange(q.range_min,q.range_max), user= user, question = q) answer.answerText = answer.answerNumeric else: answer = Answer (answerNumeric =random.randrange(0,len(q.choices)), user= user, question = q) answer.answerText = q.choices[answer.answerNumeric] elif isinstance (q,QuestionLikertScale): answer = Answer (answerNumeric =random.randrange(q.minLikert,q.maxLikert+1), user= user, question = q) answer.answerText = answer.answerNumeric else: print "tipo de pregunta invalido" quit() t = random.randrange(900, 6500) time = time + t answer.globalTime = time answer.differentialTime = t db.session.add(answer) return time
def new_answer(question, form, user): if isinstance(question, QuestionYN): answer = Answer(answerYN=(form["c" + str(question.id)].data == "Yes"), user=user, question=question) answer.answerText = str(answer.answerYN) if isinstance(question, QuestionText): if question.isNumber: if question.isNumberFloat: answer = Answer( answerNumeric=form["c" + str(question.id)].data.replace(",", "."), user=user, question=question ) else: answer = Answer(answerNumeric=form["c" + str(question.id)].data, user=user, question=question) answer.answerText = answer.answerNumeric else: answer = Answer(answerText=form["c" + str(question.id)].data, user=user, question=question) if isinstance(question, QuestionChoice): answer = Answer(answerNumeric=form["c" + str(question.id)].data, user=user, question=question) if question.render != "select": answer.answerText = form["c" + str(question.id)].choices[int(form["c" + str(question.id)].data)][1] else: # if ==select, the firts element is empty, form[0]='' answer.answerText = form["c" + str(question.id)].choices[int(form["c" + str(question.id)].data) + 1][1] if isinstance(question, QuestionLikertScale): answer = Answer(answerNumeric=form["c" + str(question.id)].data, user=user, question=question) answer.answerText = form["c" + str(question.id)].choices[int(form["c" + str(question.id)].data)][1] answer.globalTime = form["globalTimec" + str(question.id)].data answer.differentialTime = form["differentialTimec" + str(question.id)].data return answer
def test_question_expected(self): u = User(nickname = 'john', email = '*****@*****.**', role = ROLE_RESEARCHER) db.session.add(u) survey = Survey(title = "test",researcher = u) db.session.add(survey) s1 = Section (title = "1",description = "a", sequence = 1, percent = 1, survey = survey) db.session.add(s1) q1 = QuestionText(text="q1",section=s1,expectedAnswer="1",maxNumberAttempt=3) db.session.add(q1) db.session.commit() ans = Answer(user=u,question=q1,answerText="2") db.session.add(ans) db.session.commit() self.assertFalse(ans.answerAttempt()) self.assertTrue(ans.isMoreAttempt()) ans.answerText="1" self.assertTrue(ans.answerAttempt()) ans.numberAttempt=4 self.assertFalse(ans.isMoreAttempt()) q2 = QuestionYN(text="q1",section=s1,expectedAnswer="yes",maxNumberAttempt=0) db.session.add(q2) ans = Answer(user=u,question=q2,answerYN=False) db.session.add(ans) db.session.commit() self.assertTrue(ans.isMoreAttempt()) self.assertFalse(ans.answerAttempt()) ans.answerYN=True self.assertTrue(ans.answerAttempt())