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='添加成功')
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 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 ask_add(request): question_obj = Question( title=request.POST['title'], text=request.POST['text'], user=request.user) question_obj.save() return HttpResponseRedirect(reverse('question', args=(question_obj.id,)))
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()
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)
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)
def askQuestion(): data = request.get_json() body = data['body'] title = data['title'] print(title) print(body) if not title or not body: return jsonify(message="A title and body are required"), 400 userId = data['userId'] taglist = data['taglist'] question = Question( title=title, userId=userId, body=body, ) db.session.add(question) db.session.commit() questionId = question.id for tag in taglist: print("I got here") tag1 = Tag(questionId=questionId, name=tag) db.session.add(tag1) db.session.commit() question1 = question.to_dict() return jsonify(question=question1), 200
def questions(): questions = current_user.questions.all() form = CreateQuestionForm() users = User.query.all() userlist = [(u.username, u.username) for u in users] form.assign_to.choices=userlist if form.validate_on_submit(): question = Question(expression=form.expression.data) evalans = EvaluateExpression(form.expression.data) question.answer = evalans.evaluate() question.author = current_user.id challenge = Challenge(question=question) username_to = [] for name in form.assign_to.data: username_to.append(User.query.filter_by(username=name).first()) challenge.to_user = username_to db.session.add(question) db.session.add(challenge) db.session.commit() flash('Congratulations, you have created a new question.') questions = current_user.questions.all() return render_template('questions.html', title='Questions', user=current_user, questions=questions, form=form) return render_template('questions.html', title='Questions', user=current_user, questions=questions, form=form)
def patch(self, usr, listId: str, questionId: str): ''' Update a specific TODOfrom TODOS list --- tags: -Flask API responses: 200: OK, JSON Format of the new element 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=str, required=True, help="Missing delai") args = body_parser.parse_args(strict=False) try: question = Question.objects(id=toDoId, usr=usr).first() if question is None: return response(404,'Not Found', {"data": "question id not found"}) questionnary = Questionnary.objects(id=listId, usr=usr).first() if questionnary is None: return response(404,'Not Found', {"data": "questionnary id not found"}) question.update(usr=usr,question=args['question'],delai=args['delai']) question= Question.objects(id=questionId, usr=usr).first() return response(200, 'Success', {'question' : question.jsoned()}) except Exception as error5: return response(400,str(error5),args)
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
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})
def ask(request): if not request.user.is_authenticated: response = redirect('login') response['Location'] += '?continue=/ask/' return response if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = Question( author_id=request.user.profile.id, title=form.cleaned_data['title'], text=form.cleaned_data['text'], ) tags = list(set(form.cleaned_data['tags'].split(' '))) with transaction.atomic(): for tag in tags: if not Tag.objects.filter(name=tag).exists(): Tag.objects.create(name=tag) question.save() question.tags.set(tags) return redirect('question', question_id=question.id) return render(request, 'ask.html', { 'user': request.user, 'form': form, }) else: return render(request, 'ask.html', { 'user': request.user, 'form': QuestionForm(), })
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
def test_was_published_recently_with_old_question(self): """ was_published_recently() returns False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=1, seconds=1) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False)
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 question_statistics(): sumary = Question.get_sumary(request.args) time_line = Question.get_timeline(request.args) statistic = Question.get_statistic(request.args) return { 'sumary': sumary, 'time_line': time_line, 'statistic': statistic }
def createquestion(): # Get data data = request.get_json(force=True) data['uid'] = current_user.id # Add current user id # Save question to database Question.add_question(data) redir = url_for('admin.retrievepage') return jsonify(urlr = redir)
def test_was_published_recently_with_recent_question(self): """ was_published_recently() returns True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta( hours=23, minutes=59, seconds=59) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True)
def test_was_published_recently_with_future_question(self): """ was_published_recently() returns False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False)
def delete(self, id): '''Delete a question''' question_to_delete = Question.get_by_id(id) logged_in_user = get_jwt_identity() if question_to_delete: if question_to_delete['user']["id"] == logged_in_user: Question.delete_question(id) return {"message": "Successfully deleted"}, 200 return {"message": "You are not authorized to delete this question"}, 401 return {"message": "No question found"}, 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)})
def importcsv(file): with open(file, 'r') as csvfile: spamreader = csv.reader(csvfile, delimiter='|') #, quotechar='|') from app.models import Question for row in spamreader: question = Question(question=row[0], answer=row[1], distractor=row[2], created_by=None) question.save() return 0
def make_question(session, text='sample_question', position=0, quiz=None): if quiz is None: quiz = make_quiz(session) question = Question() question.quiz_id = quiz.id question.text = text question.position = position session.add(question) session.commit() return question
def postQuestion(class_id, user_id): req_data = request.get_json() question = Question(content=req_data['question'], image_url=None, student_id=user_id, instructor_id=None, class_id=class_id) db.session.add(question) db.session.commit() return question.to_dict()
def test_create(self): with open("resources/create_question.json") as fp: test_input = json.load(fp) ques = Question(self.qdb) # insert a question into mock mongo result = ques.create_question(test_input) # query mock mongo to see if question exists ins = self.client["quiz_db"]["questions"].find_one( {"_id": ObjectId(result.inserted_id)}) self.assertEqual(ins["question_hash"], "17f7b9742d27830356fc49436dd04063")
def ask(): getUser() form = AskForm() if session['qCount'] >= 5: return redirect('/') if form.validate_on_submit(): q = Question(id=str(uuid.uuid4()),body=request.form['question'],optionOne=request.form['answerOne'],optionTwo=request.form['answerTwo']) q.author=db.session.query(User).filter_by(ip=session['user']).first() session['qCount']+=1 db.session.add(q) db.session.commit() return redirect('/') return render_template('ask.html',form=form)
def postQuestion(class_id, user_id): req_data = request.get_json() question = Question( content=req_data['question'], student_id=user_id, class_id=class_id ) db.session.add(question) db.session.commit() # emit question return question.to_dict()
def favoriteQuestion(user): # Question ID as parameter & userID from header questionId = request.args.get('id') userId = user["_id"] # Converting str into Object ID questionId = ObjectId(questionId) # Getting the user adding the favorite questions to list user = User({"_id": userId}) username = user.data()['username'] status, message = False, "" curFavoriteQuestions = user.data().get('favoriteQuestions') curFavoriteQuestions = list( curFavoriteQuestions) if curFavoriteQuestions else [] question = Question({"_id": questionId}) if questionId not in curFavoriteQuestions: question.updateFavCount() curFavoriteQuestions.append(questionId) status = True message = f"{username} favorited a question" # Creating & inserting a post postObj = { "userId": userId, "message": message, "questionId": str(questionId), "questionTitle": str(question.data()['title']) } validation = validatePost(postObj) # Invalid if validation['success'] is False: return jsonify(validation) post = Post(postObj) post.insert_one() else: question.updateFavCount(False) curFavoriteQuestions.remove(questionId) status = False message = f"{username} unfavorited a question" setattr(user, 'favoriteQuestions', curFavoriteQuestions) # Updating user.update_one(user.data()) # Return the response return jsonify({ 'success': True, 'result': status, 'message': message, 'question': question.data() }), 200
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 test_attributes(self): before = datetime.utcnow() question = Question(answer='question1') question.max_tries = 7 db.session.add(question) db.session.commit() after = datetime.utcnow() self.assertEqual(question.id, 1) self.assertEqual(question.answer, 'question1') self.assertTrue(question.timestamp > before and question.timestamp < after) self.assertEqual(question.max_tries, 7) self.assertEqual(question.num_of_tries, 0) self.assertEqual(question.status, 'in_progress')
def create_question(self, title, body, user): question = Question() question.title = title question.body = body question.creator = user question.updater = user question.save() return question
def setUpClass(cls): # start Firefox try: cls.client = webdriver.Firefox() except: pass # skip these tests if the browser could not be started if cls.client: # create the application cls.app = create_app('testing') cls.app_context = cls.app.app_context() cls.app_context.push() # suppress logging to keep unittest output clean import logging logger = logging.getLogger('werkzeug') logger.setLevel('ERROR') # create the database db.create_all() User.generate_fake(10) Question.generate_fake(20) # add a new user from app.auth.views import create_username username = create_username('Jack Smith') user = User(email='*****@*****.**', nickname='Jack Smith', username=username, password='******') db.session.add(user) db.session.commit() # start the Flask server in a thread #cls.thread = threading.Thread(target=cls.app.run) cls.process = multiprocessing.Process(target=cls.app.run) cls.process.start() # give the server a second to ensure it is up time.sleep(1)
def setUpClass(cls): # start Firefox try: cls.client = webdriver.Firefox() except: pass # skip these tests if the browser could not be started if cls.client: # create the application cls.app = create_app('testing') cls.app_context = cls.app.app_context() cls.app_context.push() # suppress logging to keep unittest output clean import logging logger = logging.getLogger('werkzeug') logger.setLevel("ERROR") # create the database and populate with some fake data db.create_all() Role.insert_roles() User.generate_fake(10) Question.generate_fake(10) # add an administrator user admin_role = Role.query.filter_by(permissions=0xff).first() admin = User(email='*****@*****.**', username='******', password='******', role=admin_role, confirmed=True) db.session.add(admin) db.session.commit() # start the Flask server in a thread threading.Thread(target=cls.app.run).start() # give the server a second to ensure it is up time.sleep(1)
def populate(): question_map = { 'is-usc-worth-it': { 'title': 'Is USC worth $50,000?', 'url_string': 'is-usc-worth-it', }, 'is-usc-healthy': { 'title': 'Is USC Healthy?', 'url_string': 'is-usc-healthy', } } answers_map = { 'is-usc-worth-it': { "yes": { 'title': 'USC is actually worth it.', 'contents': 'Yes, blah blah blah. Yes blah, blah yes. Mostly blah and definitely blah.', 'author_first': 'Calvin', 'author_last': 'LeGassick', }, 'maybe': { 'title': 'It may take time to know if USC is actually worth it.', 'contents': 'Maybe, blah blah blah. Maybe blah, blah maybe. Mostly blah and definitely blah.', 'author_first': 'Marc', 'author_last': 'Pakravan', }, 'no': { 'title': 'I promise you, USC is most definitely not worth it.', 'contents': 'No, blah blah blah. No blah, blah no. Mostly blah and definitely blah.', 'author_first': 'Nathan', 'author_last': 'Wallace', } }, 'is-usc-healthy': { "yes": { 'title': 'USC is actually healhy.', 'contents': 'Yes, blah blah blah. Yes blah, blah yes. Mostly blah and definitely blah.', 'author_first': 'Rachel', 'author_last': 'Perry', }, 'maybe': { 'title': 'It may take time to know if USC is actually healthy.', 'contents': 'Maybe, blah blah blah. Maybe blah, blah maybe. Mostly blah and definitely blah.', 'author_first': 'Josh', 'author_last': 'Lurie', }, 'no': { 'title': 'I promise you, USC is most definitely not healthy it.', 'contents': 'No, blah blah blah. No blah, blah no. Mostly blah and definitely blah.', 'author_first': 'Joseph', 'author_last': 'Chen', } } } for question in question_map.keys(): q_map = question_map[question] q_map["image_url"] = "http://lorempixel.com/400/400/" q = Question(**q_map) db.session.add(q) for answer in answers_map[question]: for option in ["yes", "maybe", "no"]: a_map = answers_map[question][option] a_map["answer"] = option a_map["question_id"] = q.id a = Post(**a_map) db.session.add(a) q.is_live = True db.session.add(q) db.session.commit()