Esempio n. 1
0
    def test_list(self):
        u1 = User(username='******', email='*****@*****.**', password='******')
        u2 = User(username='******', email='*****@*****.**', password='******')
        u3 = User(username='******', email='*****@*****.**', password='******')
        q1 = Question(answer='q1')
        q2 = Question(answer='q2')
        g1 = Game()
        q1.author = u2
        q2.author = u3
        q1.recipient = u1
        q2.recipient = u1
        q1.game = g1
        q2.game = g1

        db.session.add_all([u1, u2, u3, q1, q2, g1])
        db.session.commit()
        u1.last_question_read_time = datetime.utcnow()
        q2.timestamp = datetime.utcnow()
        db.session.commit()

        with self.client:
            self.client.post(url_for('auth.login'),
                             data={
                                 'email': '*****@*****.**',
                                 'password': '******'
                             })

            # test that only q2 appears (since q1.timestamp  < u1.last_question_read_time)
            response = self.client.get(url_for('questions.list'))
            data = response.get_data(as_text=True)
            self.assertTrue('Game Against three' in data)
            self.assertFalse('Game Against two' in data)
Esempio n. 2
0
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 test_answer(self):
        u1 = User(username='******')
        u2 = User(username='******')
        q1 =Question(example="example1",system1="system1",system2="system2")
        q2 =Question(example="example1",system1="system3",system2="system4")
        q3 =Question(example="example2",system1="system1",system2="system2")

        db.session.add(u1)
        db.session.add(u2)
        db.session.add(q1)
        db.session.add(q2)
        db.session.add(q3)
        db.session.commit()

        self.assertEqual(u1.answers.all(), [])
        self.assertEqual(u2.answers.all(), [])

        a1 = q1.answer(0,u1)
        a2 = q2.answer(1,u1)

        a3 = q1.answer(1,u2)
        a4 = q3.answer(0,u2)



        db.session.add(a1)
        db.session.add(a2)
        db.session.add(a3)
        db.session.add(a4)
        db.session.commit()

        print(u1.answered_questions().all())
        self.assertEqual(u1.number_answers(),2)
        self.assertEqual(u2.answered_questions().all(),[q1,q3])
def index(page):
    try:
        db.drop_all()
        db.create_all()
        # create quiz maker
        quiz_maker = User(name='Hassan',
                          email='*****@*****.**',
                          password='******')
        # create quiz with single-choice questions
        quiz = Quiz(title="Quiz 1", limited_time=12, posted_at=datetime.now())
        # create and add question for the quiz
        question = Question(content="1+1=?",
                            correct_answer=2,
                            choices=[
                                Choice(content="1"),
                                Choice(content="2"),
                                Choice(content="3"),
                                Choice(content="4"),
                            ])
        quiz.questions.append(question)
        quiz.questions.append(
            Question(content="1+2=?",
                     correct_answer=3,
                     choices=[
                         Choice(content="1"),
                         Choice(content="2"),
                         Choice(content="3"),
                         Choice(content="4"),
                     ]))
        # add created quiz to quiz maker's created quizzes list
        quiz_maker.created_quizzes.append(quiz)

        # create quiz taker
        quiz_taker = User(name='guest', email='[email protected]', password='******')
        # quiz taker take a quiz, create user quiz result
        quiz_result = QuizResult(quiz=quiz)
        # add quiz result to the taker
        quiz_taker.quizzes_results.append(quiz_result)
        # set quiz taker's answer for question[0] in the quiz, here user choose the second choice which is at index 1
        user_choice = quiz.questions[0].choices[1]
        # create a user choice,
        user_answer = UserChoice(choice=user_choice, answer_right=True)
        # add the user answer to the quiz result
        quiz_result.user_choices.append(user_answer)
        quiz_result.user_choices.append(
            UserChoice(choice=quiz.questions[1].choices[1],
                       answer_right=False))
        # add and commit changes
        db.session.add(quiz_maker)
        db.session.add(quiz_taker)
        db.session.commit()
        # query all users
        users = User.query.all()
        # print(users[1].quizzes_results[0])
        return render_template('%s.html' % page, users=users)
    except Exception as ex:
        print(ex)
        abort(404)
def postInsertQuestion(user):

    requestData = request.get_json()
    validation = validateQuestion(requestData)

    # Parameters
    type = int(request.args.get('type')) if request.args.get('type') else 0
    type = QuestionType.SOC if type == 0 else QuestionType.ALGO

    # Invalid
    if validation['success'] is False:
        return jsonify(validation)

    try:
        # Inserting
        requestData['userId'] = user["_id"]
        userData = User({"_id": ObjectId(user['_id'])}).data()
        status, msg, questionId = Question(requestData, type=type).insert_one()

        question = Question({"_id": questionId}).data()

        # Response obj
        response = {"success": status, "message": msg}

        # Checking the status of insertion
        if status is True:
            response["question"] = requestData

        username = userData['username']
        message = f"{username} uploaded a question"

        # Creating & inserting a post
        postObj = {
            "userId": str(user["_id"]),
            "message": message,
            "questionId": str(questionId),
            "questionTitle": str(question['title'])
        }
        validation = validatePost(postObj)

        # Invalid
        if validation['success'] is False:
            return jsonify(validation)

        post = Post(postObj)
        post.insert_one()

        # Response
        return jsonify(response), 200

    except Exception as e:

        # Response
        return jsonify({"success": False, "message": str(e)})
Esempio n. 6
0
def add_question():
    user = request.args.get('user')
    movie = request.args.get('movie')
    question = request.args.get('question')

    userid = User.query.filter_by(username=user).first().id
    movieid = Movie.query.filter_by(movie_title=movie).first().id
    check_question = Question.query.filter_by(user_id=userid,
                                              movie_id=movieid,
                                              question_text=question).first()

    if check_question:
        pass
    else:
        new_question = Question(user_id=userid,
                                movie_id=movieid,
                                question_text=question)
        db.session.add(new_question)
        db.session.commit()

    verify_question = Question.query.filter_by(user_id=userid,
                                               movie_id=movieid,
                                               question_text=question).first()

    return str(verify_question.question_text)
Esempio n. 7
0
def show_question(request, student_id, exam_id, question_id):

    #if Exam(connection).is_exam_active(exam_id) != True:
    #   return redirect('/{student_id}/tests/{exam_id}'.format(student_id = student_id, exam_id = exam_id))

    if request.method == "POST":
        variable = request.POST['text_area']
        print(variable)
        return redirect("/{student_id}/tests/{exam_id}/{question_id}".format(
            student_id=student_id,
            exam_id=exam_id,
            question_id=question_id + 1))

    else:
        time_left = Exam(connection).get_exam_time_left(7)
        question, question_amount = Question(connection).get_question(
            exam_id, question_id)
        return render(
            request, "question.html", {
                "question_amount": question_amount,
                "range": range(1, question_amount + 1),
                "student_id": student_id,
                "exam_id": exam_id,
                'question': question,
                'time': time_left
            })
Esempio n. 8
0
 def test_check_lost(self):
     question = Question(answer='question1')
     question.max_tries = 7
     question.num_of_tries = 0
     self.assertFalse(question.check_lost())
     question.num_of_tries = 7
     self.assertTrue(question.check_lost())
Esempio n. 9
0
 def setUp(self):
     self.app = app.test_client()
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
     db.create_all()
     u1 = User(id=0, username='******')
     u2 = User(id=1, username='******')
     u4 = User(id=2, username='******')
     u1.setpw('Hello')
     u2.setpw('World')
     q1 = Question(id=0, constellation='Crux')
     q2 = Question(id=1, constellation='Aquarius')
     db.session.add(u1)
     db.session.add(u2)
     db.session.add(q1)
     db.session.add(q2)
     db.session.commit()
Esempio n. 10
0
    def create_action(kwargs=None):
        """Creates a Question record

        :param kwargs: dictionary to override request form values
        :type kwargs: dict

        """

        try:

            if not kwargs:

                values = request.get_json()

                kwargs = {
                    "question" : values.get('question'),
                    "answer" : values.get('answer'),
                    "category_id" : int(values.get('category', 0)),
                    "difficulty" : int(values.get('difficulty', 0))
                }

            model = Question(**kwargs)

            model.insert()

            response = {
                "success" : True,
                "question" : model.format()
            }

            return jsonify(response)

        except:

            abort(422)
Esempio n. 11
0
 def create(self, validated_data):
     question_data = StackOverflow().get_question_details(
         self.context['question_id'],
         self.context['api_site_parameter']
     )
     question_obj = Question(**{
         'bountied_user_id': self.context['request'].user.id,
         'site_question_id':  self.context['question_id'],
         'site_question_url': question_data['link'],
         'site_id': self.context['site'].id,
         'title':  question_data['title'],
         'asked_on': epoch_to_datetime(question_data['creation_date'])
     })
     question_obj.save()
     for tag in question_data['tags']:
         _tag = Tag.objects.get_or_create(name=tag)[0]
         question_obj.tags.add(_tag.id)
     bounty = Bounty(**{
         'question_id': question_obj.id,
         'amount': validated_data['bounty_amount'],
         'expiry_date': add_days_to_today(validated_data['time_limit']),
         'state': 'OPEN',
     })
     bounty.save()
     return bounty
Esempio n. 12
0
def create_new():
    data = request.json
    previousQuiz = Quiz.query.filter(Quiz.name == data["quizName"]).first()
    if previousQuiz:
        return {"error": "A Quiz with that name already exists"}
    newQuiz = Quiz(userId=data["userId"], category=data["category"], name=data["quizName"])
    db.session.add(newQuiz)
    db.session.commit()
    quizId = Quiz.query.filter(Quiz.name == data["quizName"]).order_by(Quiz.id.desc()).first().id
    for i in range(len(data["questions"])):
        newQuestion = Question(quizId=quizId, questionType="mc", content=data["questions"][i])
        db.session.add(newQuestion)
        db.session.commit()
        questionId = Question.query.filter(Question.content == data["questions"][i]).order_by(Question.id.desc()).first().id
        allAnswerChoices = data["answerChoices"][i]
        for j in range(len(allAnswerChoices)):
            newAnswerChoice = AnswerChoice(content=allAnswerChoices[j], order=j, questionId=questionId)
            db.session.add(newAnswerChoice)
            db.session.commit()
            if(int(data["answers"][i]) == j):
                answerId = AnswerChoice.query.filter(AnswerChoice.content ==
                             allAnswerChoices[j]).order_by(AnswerChoice.id.desc()).first().id
                answer = AnswerJoin(questionId=questionId, answerChoiceId=answerId)
                db.session.add(answer)
                db.session.commit()
    return {"success": True}
Esempio n. 13
0
    def fill_questions(self, cnt):
        if cnt is None:
            return False

        print('Start filling {} questions'.format(cnt))
        authors_id = list(Profile.objects.values_list('id', flat=True))
        objs = (Question(title=f.sentence()[:128],
                         author_id=choice(authors_id),
                         text=f.text()) for i in range(cnt))
        self.bulk_create(Question, objs)
        print('End filling questions')

        print('Start filling {} question tags'.format(cnt))
        tags_id = list(Tag.objects.values_list('id', flat=True))
        tags_count = dict.fromkeys(tags_id, 0)

        for item in Question.objects.all():
            for j in set(choices(tags_id, k=randint(1, 7))):
                tags_count[j] += 1
                item.tags.add(j)

        print('End filling question tags')

        print('Start updating {} tags'.format(len(tags_id)))
        tags = list(Tag.objects.all())
        for tag in tags:
            tag.count = tags_count[tag.pk]

        Tag.objects.bulk_update(tags, ['count'])
        print('End updating tags')
Esempio n. 14
0
 def test_duplicate(self):
     with open("resources/create_question.json") as fp:
         test_input = json.load(fp)
     ques = Question(self.qdb)
     ques.create_question(test_input)
     with self.assertRaises(mongomock.DuplicateKeyError):
         ques.create_question(test_input)
Esempio n. 15
0
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'))
Esempio n. 16
0
def add_qn(org_qns):
    '''Adds questions to the database, where questions are formatted to be in a dictionary
    {<question>:{'answer':<options>,'difficulty':<difficulty>}
    <questions> is str
    <options> is list of str
    <difficulty> is float (not added yet)
    '''
    if Question.query.all(): return
    for q in org_qns.keys():
        item = generate_item_bank(1)[0]
        qn = Question(question=q, discrimination=item[0], \
                    difficulty=item[1], guessing=item[2], upper=item[3], topicID=1)
        db.session.add(qn)
        db.session.commit()
        qid = qn.id
        b=True
        for o in org_qns[q]['answers']:
            opt=Option(qnID=qid,option=o)
            db.session.add(opt)
            if b:
                db.session.flush()
                qn.answerID = opt.id
                
                b=False
            
            db.session.commit()
Esempio n. 17
0
def add_question(user, qn_text, options, answer, topicID):
    '''Adds a question to the database
    Input
    qn_text : str
    options : seq of str
    answer : int (1 to 4)
    topic : int
    '''
    # Generate item parameters from CatSim
    item = generate_item_bank(1)[0]

    # Add question
    question = Question(question=qn_text, discrimination=item[0], \
        difficulty=item[1], guessing=item[2], upper=item[3], topicID = topicID, userID=user.id)
    db.session.add(question)
    db.session.flush()

    qnID = question.id
    
    # Add options and answer
    for opt in options:
        o = Option(qnID=qnID,option=opt)
        answer -= 1
        db.session.add(o)
        db.session.flush()
        if answer == 0:
            optID = o.id
            question.answerID = optID
            db.session.flush()
    db.session.commit()
    return question
Esempio n. 18
0
 def test_init(self):
     # test that a question is initialized
     self.new_question = Question(id=4, title="how to init python",
                                  body="how to init python how to init python how to init python", user_id=1,
                                  date_created=datetime.now(), date_modified=datetime.now())
     self.assertTrue(type(self.new_question.id), int)
     self.assertEqual(type(self.new_question), Question)
Esempio n. 19
0
    def fill_questions(self, cnt):
        author_ids = list(Author.objects.values_list('id', flat=True))
        authors = choices(author_ids, k=cnt)
        questions = (Question(author_id=authors[i],
                              text='. '.join(
                                  f.sentences(f.random_int(min=3, max=20))),
                              title=f.sentence()[:128],
                              date=f.date_time_this_month())
                     for i in range(cnt))
        self.create(Question, questions)

        tag_ids = list(Tag.objects.values_list('id', flat=True))
        tags_count = dict.fromkeys(tag_ids, 0)

        author_count = dict.fromkeys(author_ids, 0)
        for question in Question.objects.all():
            author_count[question.author.id] += 1
            for tag in set(choices(tag_ids, k=randint(0, 10))):
                tags_count[tag] += 1
                question.tags.add(tag)

        tags_list = list(Tag.objects.all())
        authors_list = list(Author.objects.all())
        for tag in tags_list:
            tag.count = tags_count[tag.pk]
        for author in authors_list:
            author.count += author_count[author.pk]
        Tag.objects.bulk_update(tags_list, ['count'])
        Author.objects.bulk_update(authors_list, ['count'])
Esempio n. 20
0
def addquestion():
    form = AddQuestion()
    if form.validate_on_submit():
        t_id = Test.query.filter_by(name=form.test.data).first().id
        question = Question(body=form.body.data,
                            test=t_id,
                            type=form.type.data)
        db.session.add(question)
        db.session.commit()
        q_id = question.id
        answer1 = Answers(body=form.answer_name1.data,
                          value=form.value_answer1.data,
                          quest=q_id)
        answer2 = Answers(body=form.answer_name2.data,
                          value=form.value_answer2.data,
                          quest=q_id)
        answer3 = Answers(body=form.answer_name3.data,
                          value=form.value_answer3.data,
                          quest=q_id)
        answer4 = Answers(body=form.answer_name4.data,
                          value=form.value_answer4.data,
                          quest=q_id)
        db.session.add(answer1)
        db.session.add(answer2)
        db.session.add(answer3)
        db.session.add(answer4)
        db.session.commit()
        flash('Question was add')
        return redirect(url_for('addquestion'))
    return render_template('addquestion.html', title='Add Question', form=form)
Esempio n. 21
0
def pump_questions_table():
    print('questions')

    questions = [
        'Do you have regular 1:1 meetings?',
        'Do engineering managers code less than 20% of the time?',
        'Are engineering processes measured and continuously improved (e.g. '
        'on-boarding, development, deployment, etc)?',
        'Are bugs, technical debt and refactoring tracked and openly '
        'discussed?',
        'Does senior management view addressing technical debt as an ongoing '
        'and necessary process?',
        'Are mistakes expected, and experiments encouraged, to allow the team '
        'to learn (i.e. psychological safety)?',
        'Are there clear, documented engineering practices & values the team '
        'lives by?', 'Does the team estimate work regularly?',
        'Does the team influence hiring decisions?',
        'Are poor performers dealt with effectively?',
        'Can engineers interact with users/customers?',
        'Are the QA engineers integrated with the development teams?'
    ]

    for question in questions:
        try:
            Question(body=question).save()
        except:
            pass
Esempio n. 22
0
def create_vote():
    users = [(user.id, user.login) for user in User.query.all()]
    form = PollForm()
    form.access_participation.choices = users
    form.access_results.choices = users
    if form.validate_on_submit():
        new_poll = Poll(title=form.title.data, kind='vote', repeat_type=form.repeat_type.data,
                        creator=current_user)
        for participant_id in form.access_participation:
            new_poll.access_participation.append(User.query.get(int(participant_id.data)))

        for user_id in form.access_results:
            new_poll.access_results.append(User.query.get(int(user_id.data)))

        question = form.vote_questions[0]
        if question.question.data:
            new_question = Question(type='variants', question=question.question.data,
                                    multiple_answers=question.multiple_answers.data)
            for option in question.options:
                if option.data:
                    possible_answer = PossibleAnswer(option=option.data, question=new_question)
                    new_question.possible_answers.append(possible_answer)
            new_poll.questions.append(new_question)
            db.session.add(new_poll)
            db.session.commit()
            return redirect(url_for('index'))
    if len(form.questions) == 0:
        form.vote_questions.append_entry()
    return render_template('createVote.html', form=form)
Esempio n. 23
0
def populate_questions(db, rel_path):
    """Populate db with questions from xml file.
    :param db: database obj
    :param str rel_path:
    """
    file_path = os.path.abspath(os.path.join(rel_path))

    tree = ET.parse(file_path)

    for elem in tree.xpath("./row[@PostTypeId='1']"):
        print(elem.attrib['Id'])
        accepted_answer_id = None
        if 'AcceptedAnswerId' in elem.attrib:
            accepted_answer_id = elem.attrib['AcceptedAnswerId']
            print('accepted_ans_id set')
        creation_date = datetime.fromisoformat(elem.attrib['CreationDate'])
        last_activity_date = datetime.fromisoformat(elem.attrib['LastActivityDate'])
        new_question = Question(Id=elem.attrib['Id'],
                                AcceptedAnswerId=accepted_answer_id,
                                CreationDate=creation_date,
                                Score=elem.attrib['Score'],
                                ViewCount=elem.attrib['ViewCount'],
                                Body=elem.attrib['Body'],
                                OwnerUserId=elem.attrib['OwnerUserId'],
                                LastActivityDate=last_activity_date,
                                Title=elem.attrib['Title'],
                                Tags=elem.attrib['Tags'],
                                AnswerCount=elem.attrib['AnswerCount'],
                                CommentCount=elem.attrib['CommentCount'])
        db.session.add(new_question)
Esempio n. 24
0
def questions_route():
    method = request.method

    if method == "GET":
        questions_dict = {}
        questions_dict["questions"] = []
        q_s = Question.query.filter(Question.is_live).all()
        for q in q_s:
            q_dict = {}
            for prop in question_props:
                q_dict[prop] = getattr(q, prop)

            questions_dict["questions"].append(q_dict)

        return jsonify(questions_dict)

    elif method == "POST":
        data = request.json
        if ("title" not in data) or ("url_string" not in data):
            return "Missing Field", 404

        question_map = {
            "title": data["title"],
            "url_string": data["url_string"]
        }

        q = Question(**question_map)
        db.session.add(q)
        db.session.commit()
        return "OK", 200
Esempio n. 25
0
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'}
Esempio n. 26
0
def user(username):
    page = request.args.get('page', 1, type=int)
    user = User.query.filter_by(username=username).first_or_404()
    if current_user.username == username:
        return redirect(
            url_for('index'))  # Need to be changed on 'Profile' page
    form = AskForm()
    if form.validate_on_submit():
        q = Question(
            body=form.body.data,
            anonymous=form.is_anonymous.data,
            sender_id=current_user.id,
            receiver_id=User.query.filter_by(username=username).first().id,
            answered=False)
        db.session.add(q)
        db.session.commit()
        flash('Your question was sent!')
        return (redirect('/user/' + username))
    questions = user.received.filter_by(answered=True).order_by(-Question.answer_timestamp)\
                .paginate(page, app.config['QUESTIONS_PER_PAGE'], False)
    next_url = url_for('user', username=username, page=questions.next_num) \
        if questions.has_next else None
    prev_url = url_for('user', username=username, page=questions.prev_num) \
        if questions.has_prev else None
    return render_template('user.html',
                           user=user,
                           questions=questions.items,
                           page=user.username,
                           form=form,
                           next_url=next_url,
                           prev_url=prev_url)
Esempio n. 27
0
    def put(self, usr, listId: str):
        '''
        Add question to questionnary
        ---
        tags:
            -Flask API
        responses:
            200:
                OK, JSON Format of the new list
            404:
                NO OK, Erreur
        '''
        body_parser = reqparse.RequestParser()
        body_parser.add_argument('question', type=str, required=True, help="Missing question")
        body_parser.add_argument('delai', type=int, required=True, help="Missing delai")
        args = body_parser.parse_args(strict=False)

        try:
            questionnary = Questionnary.objects(id=listId, usr=usr).first()

            if questionnary is None:
                return response(404,'Not Found', {"data": "questionnary id not found"})

            question = Question(usr=usr, question=args['question'], reponse="",delai = args['delai']).save()
            questionnary.update(pushQuestionnary=question,usr=usr)
            newQuestionnary = Questionnary.objects(id=listId, usr=usr).first()
            return response(200, 'Success', {"question": question.asJson(),"newQuestionnary": newQuestionnary.jsoned()})

        except Exception as error2:

            return response(400,str(error2),{"listId":listId})
Esempio n. 28
0
def index():

    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()
        flash('Your question has been posted.')
        return redirect(url_for('index')) # keep refresh from resubmitting post req

    questions = Question.get_recent_questions(limit=100)

    answers = [
            {
                'author': {'username': '******'},
                'body': 'You chase tennis balls.'
            },
            {
                'author': {'username': '******'},
                'body': 'To chase.'
            }
    ]
    return render_template(
            'index.html',
            title='Home',
            questions=questions,
            form=form,
            answers=answers)
Esempio n. 29
0
def addComplete(qt_name):
    q = Question()
    qt = QuestionType.query.filter_by(name=qt_name).first()
    print qt.name
    form = AddQuestionForm()
    q.context = form.context.data
    subject = '数据结构'

    q.subject_id = Subject.query.filter_by(name=subject).first().id

    if qt_name == '选择题':
        q.options = form.options.data
    q.answer = form.answer.data
    q.degree = int(request.form['kn_point_degree'])

    q.kn_point_counts = int(request.form['kn_point_counts'])
    q.kn_point_id = KnowledgePoint.query.filter_by(
        name=request.form['kn_point_id_1']).first().id
    q.question_type_id = qt.id

    db.session.add(q)
    db.session.commit()
    qt_name = ''
    return render_template('ques/add.html',
                           form=form,
                           qt_name=qt_name,
                           message='添加成功')
Esempio n. 30
0
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)