def create_question(request): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) recording_url = request.POST['RecordingUrl'] recording_url.replace('2010-04-01', '2008-08-01') to_number = request.POST['To'] from_number = request.POST['From'] number = PhoneNumber.objects.get(number=to_number) language = number.language log.debug(recording_url) q = Question(to_number=to_number, from_number=from_number, language=language, recording_url=recording_url) q.save() log.debug('Question Created: %s' % q) r = twiml.Response() r.hangup() return HttpResponse(r)
def get( self ): q = get_approving_question() if q == None or q.question == None: q = get_unapproved_question() if q == None: q = Question() """ q_submitters = get_questions_with_submitters() submitters = [] for s in q_submitters: if s.submitter and not s.submitter in submitters: submitters.append( s.submitter ) """ logging.info('Question: %s %s %s' % (q.question, q.category, q.answer)) q.state = 'approving' q.put() template_values = { 'CSS_FILE' : 'admin', 'JS_FILE' : '', 'q' : q, 'num_not_approved' : get_unapproved_question_count() } self.response.out.write( template.render( 'templates/admin.html', template_values ) )
def save(self, commit=True): # question = super(AskForm, self).save(commit=False) question = Question(title=self.cleaned_data['title'], text=self.cleaned_data['text'], author=self._user) question.save() return question
def ask(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): q = Question( created_by=request.user, author=request.user, category=form.cleaned_data['category'], title=form.cleaned_data['title'], text=form.cleaned_data['text'], ) q.save() return redirect(reverse('support:question', args=(q.id,))) else: form = QuestionForm() c = { 'form': form, 'search_form': SearchForm(), 'categories': p.CATEGORIES, 'title': _("Ask a question"), 'site_title': g.SITE_TITLE, } return render(request, 'support/ask.html', c)
def test_was_published_recently_wit_old_question(self): """ was_published_recently() should return False for question whose pub_date is in within the last day """ time = timezone.now() + datetime.timedelta(days=-30) old_question = Question(pub_date=time) self.assertEqual(old_question.was_published_recently(), False)
def question_result(qid=None): import urllib escaped_url=urllib.quote_plus("http://www.isitfutureproof.com/question/" + qid) if ('vote_value' in request.form): agree = "didn't tell us if you agree or disagree" question = Question.get(qid) if (question.total == None): question.total = 0 if (question.vote_no == None): question.vote_no = 0 if (question.vote_yes == None): question.vote_yes = 0 question.total = question.total + 1 if (request.form['vote_value'] == "yes"): question.vote_yes = question.vote_yes +1 agree = "disagree" if (request.form['vote_value'] == "no"): question.vote_no = question.vote_no +1 agree = "agree" question.save() question = Question.get(qid) percent = 0 stylepercent = "style-0" if (question.total > 0): percent = float(Decimal(str(float(1.0*question.vote_no/question.total)*100)).quantize(TWOPLACES)) stylepercent = "style-" + str(int(percent)) return render_template('question_result.html', escaped_url=escaped_url, qid=qid, question=question.question, percent=percent, vote_no=question.vote_no, total=question.total, agreed=agree, stylepercent=stylepercent) else: question = Question.get(qid) return render_template('question_clean.html', qid=qid, escaped_url=escaped_url, question=question.question)
class QuestionTests(base.ExtendedTestCase): def setUp(self): super(QuestionTests, self).setUp() self.boragle = Boragle(name='test1', slugs = ['t1'], desc = 'desc', creator = self.creator) self.boragle.put() self.avatar = Avatar(boragle = self.boragle, creator = self.creator) self.avatar.put() self.question = Question(boragle = self.boragle, text = "why ?", creator = self.avatar) self.question.put() def test_creation(self): self.app.post('/t1/ask', dict(text = 'why? why? why?', details = 'simply, maybe')) question = Question.find_by_slug('why-why-why') self.assertTrue(question) self.assertEqual("why? why? why?",question.text) self.assertEqual("simply, maybe",question.details) self.assertEqual(self.creator.name,question.creator.creator.name) def test_creation_security(self): self.logout() self.app.post('/t1/ask', dict(text = 'why? why? why?', details = 'simply, maybe'), status = 403) def test_answering_question(self): self.app.post(self.question.url, dict(answer = 'zimbly')) question = Question.get(self.question.key()) self.assertEqual('zimbly', question.answers[0].text) self.assertEqual(self.creator.name, question.answers[0].creator.name) self.assertEqual(1, question.answer_count) def test_answering_question_security(self): self.logout() self.app.post(self.question.url, dict(answer = 'zimbly'), status = 403) def test_smoke_question_page(self): self.app.get(self.question.url) def test_voting_security(self): answer = Answer.create(question = self.question, text= 'fake answer', creator = self.avatar) self.app.get(answer.voting_url+'/up', status = 302) answer = Answer.get(answer.key()) self.assertEqual(answer.vote_count, 1) self.logout() self.app.get(answer.voting_url+'/down', status = 302) answer = Answer.get(answer.key()) self.assertEqual(answer.vote_count, 1) def test_voting_up(self): answer = Answer.create(question = self.question, text= 'fake answer', creator = self.avatar) self.app.get(answer.voting_url+'/up', status = 302) answer = Answer.get(answer.key()) self.assertEqual(answer.vote_count,1) self.app.get(answer.voting_url+'/down', status = 302) answer = Answer.get(answer.key()) self.assertEqual(answer.vote_count,-1)
def list_questions_for_user(): """Lists all questions posted by a user""" form = QuestionForm() search_form = QuestionSearchForm() user = users.get_current_user() login_url = users.create_login_url(url_for('home')) query_string = request.query_string latitude = request.args.get('lat') longitude = request.args.get('lon') radius = request.args.get('r') # If searching w/ params (GET) if request.method == 'GET' and all(v is not None for v in (latitude, longitude, radius)): q = "distance(location, geopoint(%f, %f)) <= %f" % (float(latitude), float(longitude), float(radius)) index = search.Index(name="myQuestions") results = index.search(q) # TODO: replace this with a proper .query questions = [Question.get_by_id(long(r.doc_id)) for r in results] questions = filter(None, questions) # filter deleted questions if questions: questions = sorted(questions, key=lambda question: question.timestamp) else: questions = Question.all_for(user) channel_token = safe_channel_create(all_user_questions_answers_channel_id(user)) return render_template('list_questions_for_user.html', questions=questions, form=form, user=user, login_url=login_url, search_form=search_form, channel_token=channel_token)
def new_question(): """Creates a new question""" form = QuestionForm() if request.method == 'POST' and form.validate_on_submit(): question = Question( content=form.content.data, added_by=users.get_current_user(), location=get_location(form.location.data) ) try: question.put() question_id = question.key.id() create_nearby_question(question_id) flash(u'Question %s successfully saved.' % question_id, 'success') add_question_to_search_index(question) return redirect(url_for('list_questions_for_user')) except CapabilityDisabledError: flash(u'App Engine Datastore is currently in read-only mode.', 'info') return redirect(url_for('list_questions_for_user')) else: flash_errors(form) return redirect(url_for('list_questions_for_user'))
def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertEqual(future_question.was_published_recently(), False)
def get(self): numADQuestions = Question.gql('WHERE product = :1', 'ADSync').count() numSPQuestions = Question.gql('WHERE product = :1', 'SharePoint Web Part').count() numSSOQuestions = Question.gql('WHERE product = :1', 'SSO').count() values = { 'numADQuestions': numADQuestions, 'numSPQuestions': numSPQuestions, 'numSSOQuestions': numSSOQuestions } self.response.out.write(template.render('templates/index.html', values))
def test_get_user(): user = User() user.username = u"test" user.set_password("test123") assert user.save() assert user._id q = Question() q.question = u"test" q.author = u"anon" q.user = user.username assert q.save(validate=True) assert q._id user_from_question = q.get_user() assert user_from_question._id == user._id q.user = u"anon!" q.save() assert not q.get_user()
def ask_display(request): if not request.user.is_authenticated(): raise PermissionDenied if request.method == 'POST': request_title = request.POST.get('title') request_text = request.POST.get('text') request_tags = request.POST.get('tags') if request_title == '' or request_text == '': return render(request, 'ask.html', {'page_title': 'New Question', 'errors': '1'}) new_question = Question(title = request_title, date = datetime.datetime.now(), author = UserProfile.objects.get(user_account = request.user), text = request_text) new_question.save() for tag_str in request_tags.split(','): if Tag.objects.filter(name = tag_str).exists(): tag = Tag.objects.get(name = tag_str) new_question.tags.add(tag) else: new_tag = Tag(name = tag_str) new_tag.save() new_question.tags.add(new_tag) return HttpResponseRedirect('/question/{}'.format(new_question.id)) return render(request, 'ask.html', {'page_title': 'New Question', 'errors': '0'})
def save_scratch(kind='', subject='', theme='', text='', answers=[]): ''' save question from scratch to database ''' q = Question(kind=kind, subject=subject, theme=theme, text=text, answers=answers) q.save() return True
def create_test_backup(request): test_obj = json.loads(request.body) test = Test() #import pdb; pdb.set_trace() if request.user.is_authenticated(): owner = User_Profile.objects.filter(user = request.user) test.owner = owner[0] test.test_name = test_obj['PRE_TEST']['test_name'] #test.subject = test_obj['PRE_TEST'].subject #test.target_exam = test_obj['PRE_TEST'].target_exam #test.topics = test_obj['PRE_TEST'].topics_included test.total_time = test_obj['PRE_TEST']['total_time'] test.pass_criteria = test_obj['PRE_TEST']['pass_criteria'] test.assoicated_class = Class.objects.get(pk=test_obj['CLASS_INFO']) test.save() try: for item in test_obj['QUESTIONS']: question = Question() question.question_text = item['question_text'] question.explanation = item['explanation'] question.options = json.dumps(item['options']) question.hint = item['hint'] question.difficulty = item['difficulty_level'] question.points = item['points'] question.owner = owner[0] #question.target_exam = test.target_exam #question.subject = test.subject #question.topic = item.topic question.save() test.questions.add(question) data = {"status" : "success"} return JsonResponse(data) except Exception, e: raise e
def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whos pub_date is within the last day. """ time = timezone.now() + datetime.timedelta(hours=-1) recent_question=Question(pub_date=time) self.assertEqual(recent_question.was_published_recently(), True)
def askquestion(request): """提问模板""" name =request.session.get('name') if request.method == "POST" and request.is_ajax(): form = QuestionForm(request.POST) if form.is_valid(): data = form.cleaned_data title = data['title'] text = data['text'] qtype = data['q_type'].lower() user = User.objects.get(name=name.split()[0]) try: questiontype = QuestionType.objects.get(name=qtype) except QuestionType.DoesNotExist: questiontype = QuestionType(name=qtype) questiontype.save() question = Question(user=user, title=title, text=text, q_type=questiontype) question.save() # return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) return JsonResponse({'status':'ok'}) else: # return HttpResponse(request.POST.get('title')) return render(request, 'askquestion.html') if name: return render(request,'askquestion.html',{'QuestionForm':QuestionForm, 'name':name.split()}) else: return HttpResponseRedirect("/")
def save(self): question = Question(**self.cleaned_data) if question.author_id: question.author_id += 1 else: question.author_id = 1 question.save() return question
def save(self): if self._user.is_anonymous(): self.cleaned_data['author_id'] = 1 else: self.cleaned_data['author'] = self._user question = Question(**self.cleaned_data) question.save() return question
def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertEqual(old_question.was_published_recently(), False)
def get_question(): questions = Question.all() if questions.count() == 0: new_question = Question(text="Dummy text") new_question.save() else: new_question = questions[0] return new_question
def question_add(request): survey_add=Survey.objects.get(id=int(request.session['current_survey'])) new_question=Question() new_question.question_text=request.POST['question_text'] survey_add.question_set.add(new_question) new_question.save() survey_add.save() request.session['current_question']=new_question.id return redirect('admin-choice-add-view')
def getUnansweredQuestionsFor(username): vote_ids = [a.question for a in getAnsweredQuestionsFor(username)] question_ids = [str(q.key()) for q in Question.all()] filtered_ids = [] for qid in question_ids: if qid not in vote_ids: filtered_ids.append(qid) questions = Question.get(filtered_ids) return questions
def create(request): if request.method == "GET": return render(request,'question/create.html',{}) q = Question() q.title = request.POST["title"] q.text = request.POST["text"] q.save() return redirect('lookup',q.id)
def createQuestion(match_id): player_id = request.form['player_id'] correct = request.form['correct'] == '1' tags = request.form.getlist('tags[]') answer = Answer(player_id, correct) question = Question(tags, answers=[answer.asJSON()]) question.save() match = MatchFinder().find(match_id) match.addQuestionAndAnswer(question, answer) return "OK " + str(question._id)
def post(self): message = xmpp.Message(self.request.POST) try: question = " ".join([x for x in message.body.split() if not x.startswith('@')]) lang, confidence = detect_language_from_msg(question) except: logging.warning("Error during language detection. Switching back to en") lang = "en" answr = Answr.answr(lang).text Question.save(message.body, answr, 'xmpp', message.sender, lang) message.reply(answr)
def save_questions(questions): """Iteratively write questions to the database. """ for q in questions: cat = Category.objects.filter(name=q[0]) if cat: qu = Question(category=cat[0], question=q[1], answer=q[2]) qu.save() else: print("Please load categories first.")
def post(self, boragle_slug): boragle = Boragle.find_by_slug(boragle_slug) avatar = self.get_avatar_for_boragle(boragle) text = self.read('text') if not text or not text.strip(): raise PostingError('Please enter a question.') assert avatar new_question = Question(text = text, details = self.read('details'), boragle = boragle, creator = avatar) new_question.put() self.redirect(new_question.url)
def create_search_questions(): # loading request body body = request.get_json() # if search if (body.get('searchTerm')): search_term = body.get('searchTerm') # selection query the database using search term selection = Question.query.filter( Question.question.ilike(f'%{search_term}%')).all() # no results found if (len(selection) == 0): abort(404) # paginate paginated = pagination(request, selection) # view return jsonify({ 'success': True, 'questions': paginated, 'total_questions': len(Question.query.all()) }) # else create a question else: # loading data from body new_question = body.get('question') new_answer = body.get('answer') new_difficulty = body.get('difficulty') new_category = body.get('category') # check if any field is None if ((new_question is None) or (new_answer is None) or (new_difficulty is None) or (new_category is None)): abort(422) try: # create question question = Question(question=new_question, answer=new_answer, difficulty=new_difficulty, category=new_category) # insert question question.insert() # selection query(questions) by id selection = Question.query.order_by(Question.id).all() # paginate current_questions = pagination(request, selection) # view return jsonify({ 'success': True, 'created': question.id, 'question_created': question.question, 'questions': current_questions, 'total_questions': len(Question.query.all()) }) except: abort(422)
def post_question(): body = request.get_json() search_term = body.get('searchTerm') # if the json from the response is not valid -> abort # if search_term is None: # abort(400) # if a search term is provided perform a search try: if search_term: # search_questions = Question.query.filter(Question.question.contains(search_term)).all() search_questions = Question.query.filter( Question.question.ilike('%{}%'.format(search_term))).all() # if no questions are found return 404 error if (len(search_questions) == 0): abort(404) # if there are questions found, return them paginated paginated_search_questions = paginate_questions( request, search_questions) # get categories and return the result #categories = Category.query.order_by(Category.id).all() # Format Categories in a dictionary #active_categories = {} #for category in categories: #active_categories[category.id] = category.type return jsonify({ 'success': True, 'questions': paginated_search_questions, 'total_questions': len(paginated_search_questions) #, #'current_categories': active_categories }) # if no search term is provided, add the question else: new_question = body.get('question', None) new_answer = body.get('answer', None) new_difficulty = body.get('difficulty', None) new_category = body.get('category', None) # check if any required input is missing and abort if new_question is None: abort(400) if new_answer is None: abort(400) if new_difficulty is None: abort(400) if new_category is None: abort(400) try: # try to generate a new question question = Question(question=new_question, answer=new_answer, category=new_category, difficulty=new_difficulty) question.insert() # Get all questions questions = Question.query.order_by(Question.id).all() paginated_questions = paginate_questions( request, questions) # return results return jsonify({ 'success': True, 'created': question.id, 'question_created': question.question, 'questions': paginated_questions, 'total_questions': len(questions) }) except Exception as e: print(e) abort(422) except Exception as e: print(e) abort(422)
def question(): if request.method == 'GET': user_id = session.get('user_id') user = User.query.filter(User.id == user_id).first() return render_template('question.html', user=user) else: title = request.form.get('title') content = request.form.get('content') type = request.form.get('type') if type == '1': kind = 1 elif type == '2': kind = 2 elif type == '3': kind = 3 elif type == '4': kind = 4 elif type == '5': kind = 5 elif type == '6': kind = 6 elif type == '7': kind = 7 else: kind = 8 if 'attach_file' in request.files: #如果用户上传了文件 filename = docs.save(request.files['attach_file']) question = Question(title=title, file=filename, content=content, report_reasons_and_times='A@0|B@0|C@0|D@0', report_total=0, type=kind) else: question = Question(title=title, content=content, report_reasons_and_times='A@0|B@0|C@0|D@0', report_total=0, type=kind) user_id = session.get('user_id') user = User.query.filter(User.id == user_id).first() user.number_of_post = user.number_of_post + 1 user.point = user.point + 20 if user.point >= 50 and user.point < 100: user.grade = 2 elif user.point >= 100 and user.point < 200: user.grade = 3 elif user.point >= 200 and user.point < 500: user.grade = 4 elif user.point < 50 and user.point >= 0: user.grade = 1 else: user.grade = 5 question.author = user # question.author_id = user_id flask_whooshalchemyplus.index_one_model(Question) db.session.add(question) db.session.commit() return redirect(url_for('index'))
def post(self): parse = reqparse.RequestParser() parse.add_argument('word', type=str) parse.add_argument('atype', type=int) parse.add_argument('meaning', type=str) parse.add_argument('fromWhat', type=str) parse.add_argument('example', type=str) args = parse.parse_args() word = args.get('word') atype = args.get('atype') meaning = args.get('meaning') fromWhat = args.get('fromWhat') example = args.get('example') # 查找词条是否存在 print('0') try: print('1') question = Question.query.filter_by(word=word).first() print('2') print(question.to_json()) except: print("{} question query failure: {} failure...".format( time.strftime("%Y-%m-%d %H:%M:%S"), word)) print('3') if not question: # 词条不存在 # 新建question try: question = Question(word=word) db.session.add(question) db.session.commit() except: print("{} question add: {} failure...".format( time.strftime("%Y-%m-%d %H:%M:%S"), word)) db.session.rollback() print('4') qid = question.qid print(qid) try: print('5') answer = Answer(qid=qid, atype=atype, meaning=meaning, fromWhat=fromWhat, example=example, created_time=int(time.time())) print('6') db.session.add(answer) print('7') db.session.commit() print('8') except: print("{} answer add: {} failure...".format( time.strftime("%Y-%m-%d %H:%M:%S"), qid)) response = make_response( jsonify(code=21, message='answer add fail')) return response response = make_response( jsonify(code=0, message='OK', data={'question': question.to_json()})) return response
def importperson(request): ''' 普通用户导入自己的数据 管理员导入任意人的数据 ''' personinfo_name = [ 'name', 'sex', 'age', 'adno', 'home' 'profession', 'education', 'disease_history', 'disease_age_h', 'disease_current', 'disease_age_c', 'used_drugs', 'using_drugs' ] questioninfo_name = [ 'q1', 'q2', 'q3', 'q4', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'q6', 'q7', 'q8', 'q9', 'time_submit' ] if request.method == "GET": return render_to_response('importperson.html', locals()) fi = request.FILES['personcsv'] questions = [] fi.readline() for line in fi.readlines(): try: line = line.decode('utf8') except: try: line = line.decode('gbk') except: pass spli = ',' if line.count(',') > line.count('\t') else '\t' attrs = line.replace('\n', '').replace('\r', '').split(spli) if request.user.is_superuser: try: person = Person.objects.get(username=attrs[0]) except Person.DoesNotExist: person = Person(username=attrs[0]) person.name,person.sex,person.age,person.adno,person.home,person.profession,person.education,person.disease_history,\ person.disease_age_h,person.disease_current,person.disease_age_c,person.used_drugs,person.using_drugs=attrs[1:14] person.save() question_list = attrs[14:-1] else: person = Person.objects.get(username=request.user.username) question_list = attrs[:-1] question_dict = dict(zip(questioninfo_name, map(int, question_list))) question = Question(person=person, **question_dict) question.time_submit = datetime.datetime.strptime(attrs[-1], '%Y%m%d') element_A = question.q6 if question.q2 <= 15: element_B = question.a elif question.q2 <= 30: element_B = 1 + question.a elif question.q2 < 60: element_B = 2 + question.a elif question.q2 > 60: element_B = 3 + question.a if question.q4 > 7: element_C = 0 elif question.q4 > 6: element_C = 1 elif question.q4 >= 5: element_C = 2 elif question.q4 < 5: element_C = 3 if question.q3 > question.q1: Sleep_efficiency = 1.0 * question.q4 / (24 - question.q3 + question.q1) else: Sleep_efficiency = 1.0 * question.q4 / (question.q1 - question.q3) if Sleep_efficiency > 0.85: element_D = 0 elif Sleep_efficiency > 0.75: element_D = 1 elif Sleep_efficiency >= 0.65: element_D = 2 elif Sleep_efficiency < 0.65: element_D = 3 Sleep_disorder = question.b + question.c + question.d + question.e + question.f + question.g + question.h + question.i + question.j if Sleep_disorder == 0: element_E = 0 elif Sleep_disorder <= 9: element_E = 1 elif Sleep_disorder <= 18: element_E = 2 elif Sleep_disorder <= 27: element_E = 3 element_F = question.q7 Daytime_dysfunction = question.q8 + question.q9 if Daytime_dysfunction == 0: element_G = 0 elif Daytime_dysfunction <= 2: element_G = 1 elif Daytime_dysfunction <= 4: element_G = 2 elif Daytime_dysfunction <= 6: element_G = 3 question.score = element_A + element_B + element_C + element_D + element_E + element_F + element_G question.save() questions.append(question) return render_to_response('importperson.html', locals())
def delete_question(question_id): q = Question.query.filter_by(id=question_id).one_or_none() if q is None: abort(422) Question.delete(q) return jsonify({'success': True, 'question': q.id})
""" Make a file named questions.csv with the first line name,flag,desc,link (or whatever the schema is, for that check models.py) Fill in the data in the CSV and run this script this will add the entries into the sql database """ from database import init_db, db_session from models import Question import csv questions = open("questions.csv") init_db() Question.query.delete() questionsCSV = csv.DictReader(questions) for question in questionsCSV: q = Question(name=question['name'],flag=question['flag'],desc=question['desc'],points=question['points'], category=question['category'], filename=question['filename']) db_session.add(q) questions.close() db_session.commit()
it's possible to create a new database in a local file or memory for each test case. You don't need a system service running, no need to configure user, etc. ''' db_path = 'sqlite:///trivia.sqlite3' app = Flask(__name__) setup_db(app, db_path) categories = {} with open('test_data/categories.csv') as cat_csv: cat_reader = csv.reader(cat_csv, delimiter=',') header = next(cat_reader) print(header) for row in cat_reader: cat_id, cat_name = row categories[cat_id] = cat_name db.session.add(Category(type=cat_name)) with open('test_data/questions.csv') as q_csv: q_reader = csv.reader(q_csv, delimiter=',') header = next(q_reader) print(header) for row in q_reader: _, question, answer, difficulty, category_id = row db.session.add(Question(question, answer, difficulty, category_id)) db.session.commit()
def create_questions(): ''' POST /api/questions -d {"searchTerm": "title"} to get questions based on a search term. Response: Questions for whom the search term is a substring of the question { "current_category": "All", "questions": [ { "answer": "Maya Angelou", "category": 4, "difficulty": 2, "id": 5, "question": "Whose autobiography is entitled?" }, { "answer": "Edward Scissorhands", "category": 5, "difficulty": 3, "id": 6, "question": "What was the title of the 1990 fantasy directed?" } ], "success": True, "total_questions": 2 } POST /api/questions -d { "question": "question", "answer": "answer", "category": 2, "difficulty": 3 } To create new question Response: newly created question and success message { "success": True, "question": { "question": "question", "answer": "answer", "category": 2, "difficulty": 3 "id": 12, } } Error: 422 for any validation errors ''' try: data = request.get_json() searchTerm = data.get('searchTerm', None) if is_valid(searchTerm): questions = Question.query.order_by(Question.id).filter( Question.question.ilike('%{}%'.format(searchTerm))).all() paginated_questions = paginate_questions(request, questions) return jsonify({ 'questions': paginated_questions, 'success': True, 'total_questions': len(questions), 'current_category': 'All' }) else: question = data.get('question', None) answer = data.get('answer', None) category = data.get('category', None) difficulty = data.get('difficulty', None) # validate data before creating validate_or_abort(question) validate_or_abort(answer) validate_or_abort(category) validate_or_abort(difficulty) newQuestion = Question(question=question, answer=answer, category=category, difficulty=difficulty) newQuestion.insert() return jsonify({ 'success': True, 'question': newQuestion.format() }) except Exception: abort(422)
class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.svr = "localhost:5432" self.dbname = "trivia_test" self.dbusr = "******" self.dbpass = "******" self.dbpath = \ f"postgresql://{self.dbusr}:{self.dbpass}@{self.svr}/{self.dbname}" setup_db(self.app, self.database_path) # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() self.new_question = Question(question="new question", answer="new answer", category=1, difficulty=1) self.new_category = Category("Test") self.new_question.insert() self.new_category.add() def tearDown(self): """Executed after reach test""" self.new_question.delete() self.new_category.delete() pass """ TODO Write at least one test for each test for successful operation and for expected errors. """ def test_paginated_questions(self): res = self.client().get('/questions') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) # test that pagination works self.assertLessEqual(data['total_questions'], 10) self.assertTrue(len(data['questions'])) def test_categories(self): res = self.client().get('/categories') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertTrue(len(data['categories'])) def test_get_category_questions(self): res = self.client().get( f'/categories/{self.new_question.category}/questions') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertEqual(int(data['category']), self.new_question.category) self.assertTrue(len(data['questions'])) self.assertTrue(data['total']) def test_get_category_questions_404(self): res = self.client().get(f'/categories/9999/questions') data = json.loads(res.data) self.assertEqual(res.status_code, 404) self.assertEqual(data['success'], False) self.assertEqual(data['message'], "Sorry, resource unavailable") def test_unreachable_page_number(self): res = self.client().get('/questions?page=9999') data = json.loads(res.data) self.assertEqual(res.status_code, 404) self.assertEqual(data['success'], False) self.assertEqual(data['message'], "Sorry, resource unavailable") def test_unreachable_category_number(self): res = self.client().get('/categories/999') data = json.loads(res.data) self.assertEqual(res.status_code, 404) self.assertEqual(data['success'], False) self.assertEqual(data['message'], "Sorry, resource unavailable") def test_delete_question(self): # create question to be deleted question = Question("new question", "new answer", 1, 1) question.insert() question_id = question.id # delete question and get response res = self.client().delete(f"questions/{question_id}") data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) # check if deleted question no longer exists deleted_question = Question.query.get(question_id) self.assertEqual(deleted_question, None) def test_delete_question_404(self): res = self.client().delete("questions/askfueso") data = json.loads(res.data) self.assertEqual(res.status_code, 404) self.assertEqual(data['success'], False) self.assertEqual(data['message'], "Sorry, resource unavailable") def test_add_question(self): new_question = { 'question': 'Who is the first man?', 'answer': 'Adam', 'category': 1, 'difficulty': 1 } oldTotal = len(Question.query.all()) # Add question res = self.client().post('questions', json=new_question) data = json.loads(res.data) newTotal = len(Question.query.all()) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) # test that the number of questions has increased by 1 self.assertEqual(newTotal, oldTotal + 1) def test_add_question_failure(self): new_question = { 'question': 'Who is the first man?', 'answer': 'Adam', 'category': 1 } oldTotal = len(Question.query.all()) # Add question res = self.client().post('questions', json=new_question) data = json.loads(res.data) newTotal = len(Question.query.all()) self.assertEqual(res.status_code, 422) self.assertEqual(data['success'], False) self.assertEqual(data['message'], "Sorry, request cannot be processed") # test that the number of questions has not increased by 1 self.assertEqual(newTotal, oldTotal) def test_question_search(self): query = {'searchTerm': 'e'} res = self.client().post('/questions/search', json=query) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertIsNotNone(data['questions']) self.assertIsNotNone(data['total_questions']) def test_quiz(self): quiz = { 'previous_questions': [], 'quiz_category': { 'type': 'Test', 'id': 1 } } res = self.client().post('/quizzes', json=quiz) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) def test_quiz_404(self): quiz = {'quiz_category': {'type': 'Test', 'id': 1}} res = self.client().post('/quizzes', json=quiz) data = json.loads(res.data) self.assertEqual(res.status_code, 422) self.assertEqual(data['success'], False) self.assertEqual(data['message'], "Sorry, request cannot be processed")
class TriviaTestCase(unittest.TestCase): def setUp(self): self.app = create_app() self.client = self.app.test_client() self.database_name = "trivia_test" self.database_path = "postgres://{}/{}".format( 'trivia:trivia@localhost:5432', self.database_name) self.db = setup_db(self.app, self.database_path) self.category = Category("Science") self.question = Question('test_question', 'test_answer', self.category.id, 5) self.new_question_correct = { 'question': 'test_question', 'answer': 'test_answer', 'category': 'science', 'difficulty': '5' } self.new_question_false = { 'answer': 'test_answer', 'category': 'science', 'difficulty': '5' } self.search = {'searchTerm': 'test'} self.id = 0 # binds the app to the current context # with self.app.app_context(): #self.db = SQLAlchemy() self.db.init_app(self.app) self.db.session.rollback() self.db.drop_all() self.db.create_all() def tearDown(self): # with self.app.app_context(): self.db.drop_all() pass # GET '/api/v1/categories' Bad Input Categories not loaded to database def test_get_categories_bad(self): res = self.client.get('/api/v1/categories') data = json.loads(res.data) self.assertEqual(res.status_code, 404) # GET '/api/v1/categories' Happy Scenario def test_get_categories_happy(self): self.category.insert() res = self.client.get('/api/v1/categories') data = json.loads(res.data) self.assertEqual(res.status_code, 200) # GET '/api/v1/questions' Bad Input def test_getQuestions_bad(self): res = self.client.get('/api/v1/questions') self.assertEqual(res.status_code, 404) # GET '/api/v1/questions' Happy Scenario def test_getQuestions_happy(self): self.category.insert() Question('test_question', 'test_answer', self.category.id, 5).insert() res = self.client.get('/api/v1/questions') self.assertEqual(res.status_code, 200) # POST '/api/v1/questions' Happy Scenario def test_submitQuestion_happy(self): self.category.insert() res = self.client.post('/api/v1/questions', json=self.new_question_correct) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) # POST /api/v1/questions Bad Input def test_submitQuestion_bad(self): res = self.client.post('/api/v1/questions', json=self.new_question_false) data = json.loads(res.data) self.assertEqual(res.status_code, 422) self.assertEqual(data['success'], False) # DELETE '/api/v1/questions/<int:question_id>' Happy Scenario def test_delete_question_happy(self): self.category.insert() self.question = Question('test_question', 'test_answer', self.category.id, 5) self.question.insert() res = self.client.delete('/api/v1/questions/' + str(self.question.id)) self.assertEqual(res.status_code, 200) # DELETE '/api/v1/questions/<int:question_id>' Bad Input def test_delete_question_bad(self): res = self.client.delete('/api/v1/questions/' + str(self.question.id)) data = json.loads(res.data) self.assertEqual(res.status_code, 404) self.assertEqual(data['success'], False) # POST '/api/v1/questions/search' Happy Scenario def test_search_question_happy(self): self.category.insert() self.question = Question('test_question', 'test_answer', self.category.id, 5) self.question.insert() res = self.client.post('/api/v1/questions/search', json=self.search) self.assertEqual(res.status_code, 200) # POST '/api/v1/questions/search' Bad Input def test_search_question_bad(self): self.category.insert() self.question = Question('test_question', 'test_answer', self.category.id, 5) self.question.insert() res = self.client.post('/api/v1/questions/search') self.assertEqual(res.status_code, 422) # GET '/api/v1/categories/<string:category_id>/questions' Happy Scenario def test_get_question_by_categories_happy(self): self.category.insert() self.question = Question('test_question', 'test_answer', self.category.id, 5) self.question.insert() url = '/api/v1/categories/{}/questions'.format(self.category.type) res = self.client.get(url) data = json.loads(res.data) self.assertEqual(res.status_code, 200) # GET '/api/v1/categories/<int:category_id>/questions' Bad Input def test_get_question_by_categories_bad(self): res = self.client.get('/api/v1/categories/test/questions') data = json.loads(res.data) self.assertEqual(res.status_code, 422) # GET '/api/v1/quizzes' Happy def test_quizzes_happy(self): self.category.insert() self.question = Question('test_question', 'test_answer', self.category.id, 5) self.question.insert() request_json = { 'previous_questions': [], 'quiz_category': { "type": self.category.type } } res = self.client.post('/api/v1/quizzes', json=request_json) data = json.loads(res.data) self.assertEqual(res.status_code, 200) # GET '/api/v1/quizzes' Bad def test_quizzes_bad(self): res = self.client.post('/api/v1/quizzes') data = json.loads(res.data) self.assertEqual(res.status_code, 422)
def post_question(): ''' Create new question and search questions endpoint. ''' body = request.get_json() # if search term is present if (body.get('searchTerm')): search_term = body.get('searchTerm') # query the database using search term selection = Question.query.filter( Question.question.ilike(f"%{search_term}%")).all() # 404 if no results found if (len(selection) == 0): abort(404) # paginate the results paginated = paginate_questions(request, selection) # return results return jsonify({ 'success': True, 'questions': paginated, 'total_questions': len(Question.query.all()) }) # if no search term, create new question else: # load input from body new_question = body.get('question') new_answer = body.get('answer') new_difficulty = body.get('difficulty') new_category = body.get('category') # validate that all inputs have data if ((new_question is None) or (new_answer is None) or (new_difficulty is None) or (new_category is None)): abort(422) try: # create and insert new record question = Question(question=new_question, answer=new_answer, difficulty=new_difficulty, category=new_category) question.insert() # query all questions and paginate selection = Question.query.order_by(Question.id).all() current_questions = paginate_questions(request, selection) return jsonify({ 'success': True, 'created': question.id, 'question_created': question.question, 'questions': current_questions, 'total_questions': len(Question.query.all()) }) except unprocessable: # abort with unprocessable entity response abort(422)
def post_question(): if request.data: data = request.get_json() ''' @TODO: Create a POST endpoint to get questions based on a search term. It should return any questions for whom the search term is a substring of the question. TEST:Search by any phrase.The questions list will update to include only question that include that string within their question. Try using the word "title" to start. ''' # check if request body contains searchTerm to proceed # retrieving questions based on search trerm, # otherwise it wull create a new question if 'searchTerm' in data: try: searchTerm = data["searchTerm"] questions = Question.query.filter( Question.question.ilike('%' + searchTerm + '%')).all() questionlist = [q.format() for q in questions] categorieslist = [ category.format() for category in Category.query.all() ] return jsonify({ "success": True, "questions": questionlist, "totalQuestions": len(questionlist), "current_category": None }) except: abort(422) else: ''' @TODO: Create an endpoint to POST a new question, which will require the question and answer text, category, and difficulty score. TEST: When you submit a question on the "Add" tab, the form will clear and the question will appear at the end of the last page of the questions list in the "List" tab. ''' try: question = data["question"] answer = data["answer"] difficulty = data["difficulty"] category = data["category"] ques = Question(question=question, answer=answer, difficulty=difficulty, category=category) try: ques.insert() except: abort(422) return jsonify({"success": True}) except EOFError: abort(200) else: abort(400)
def create_or_search_questions(): body = request.get_json() if not body: abort(400, {'message': 'request does not contain a valid JSON body.'}) search_term = body.get('searchTerm', None) if search_term is None: ''' @TODO(Done): Create an endpoint to POST a new question, which will require the question and answer text, category, and difficulty score. TEST: When you submit a question on the "Add" tab, the form will clear and the question will appear at the end of the last page of the questions list in the "List" tab. ''' new_question = body.get('question', None) new_answer = body.get('answer', None) new_category = body.get('category', None) new_difficulty = body.get('difficulty', None) if not new_question: abort(400, {'message': 'Fill Question Field'}) if not new_answer: abort(400, {'message': 'Fill Answer Field'}) if not new_category: abort(400, {'message': 'Fill Category Field'}) if not new_difficulty: abort(400, {'message': 'Fill Difficulty Field'}) try: question = Question(question=new_question, answer=new_answer, category=new_category, difficulty=new_difficulty) question.insert() selections = Question.query.order_by(Question.id).all() paginated_questions = paginate_questions(request, selections) return jsonify({ 'success': True, 'created': question.id, 'questions': paginated_questions, 'total_questions': len(selections) }) except BaseException: abort(422) else: ''' @TODO(Done): Create a POST endpoint to get questions based on a search term. It should return any questions for whom the search term is a substring of the question. TEST: Search by any phrase. The questions list will update to include only question that include that string within their question. Try using the word "title" to start. ''' questions = Question.query.filter( Question.question.like("%{}%".format(search_term))).all() if not questions: abort( 404, { 'message': 'Question containing "{}": No Found.'.format( search_term) }) questions_found = [question.format() for question in questions] selections = Question.query.order_by(Question.id).all() categories = Category.query.all() categories_all = [category.format() for category in categories] return jsonify({ 'success': True, 'questions': questions_found, 'total_questions': len(selections), 'current_category': categories_all })
def post(self): # Grab album from url urlstring = self.request.POST['album'] album_key = ndb.Key(urlsafe=urlstring) album = album_key.get() # Check whether we're storing a album or a Question if self.request.GET['album'] == '1': album.title = self.request.POST['albumTitle'] album.category = self.request.POST['categoryTitle'] album.put() time.sleep(0.1) # Save album and redirect to edit if the user clicks on 'Save and continue editing' # Else, save album and go back to the main page which lists all albums if self.request.POST.get('stay') == '1': self.redirect('/edit?album=1&id=' + urlstring) else: if album.album_type == 'match': self.redirect('/match') elif album.album_type == 'correlate': self.redirect('/correlate') else: self.redirect('/oddmanout') else: # Create Question with the album as parent for strong consistency question = "" new = "1" if self.request.POST['question'] == "": question = Question(parent=album_key) question.question_id = question.put().id() else: new = "0" question_url = self.request.POST['question'] question_key = ndb.Key(urlsafe=question_url) question = question_key.get() question.title = self.request.get('title') question.fact = self.request.get('fact') question.effect = self.request.get('revealEffect') question.difficulty = self.request.get('difficulty') # Create answer choices answer = int(self.request.get('correct_answer')) input_images = self.request.get('image', allow_multiple=True) num_images = 4 if album.album_type == 'correlate': num_images = 5 image_list = [] for i in range(num_images): img = "" input_img = input_images[i] # If old retrieve the Image if new == "0": img = question.images[i] else: img = Image() # Resize image if input_img: op_img = images.Image(input_img) op_img.resize(width=256, height=256, crop_to_fit=True) result_img = op_img.execute_transforms( output_encoding=images.JPEG) img.image = result_img # Set the title and correct fields if answer == i: img.title = "correct_answer_" + str(i) img.correct = True elif num_images == 5 and i == 0: # This is if the album is of type Correlate img.title = "main_image_" + str(i) img.correct = False else: img.title = "incorrect_answer_" + str(i) img.correct = False # If old Question, free up the old Image and put in new Image if new == "0": question.images.pop(i) question.images.insert(i, img) else: question.images.append(img) question.put() # Query all Question(s) for the album in recently added order for /create # Retrieve previously input values, and indicate whether this is a new album (edit) questions = Question.query( ancestor=album_key).order(-Question.date).fetch() retrieve = 1 edit = self.request.GET['edit'] template_values = { 'album': album, 'album_type': album.album_type, 'questions': questions, 'edit': edit, 'retrieve': retrieve } template = JINJA_ENVIRONMENT.get_template('create.html') self.response.write(template.render(template_values))
from app import db from models import Question objects = [ Question(text="Tell me something about yourself.", order_pos=1), Question(text="Explain how you interact with colleagues.", order_pos=2), Question(text="Describe a conflict resolution situation you experienced.", order_pos=3), Question( text="How do you face a situation requiring skills you don’t have?", order_pos=4), Question(text="Do you do anything for fun?", order_pos=5), Question(text="Describe your working habits.", order_pos=6) ] db.session.add_all(objects) db.session.commit()
def save(self): question = Question(**self.cleaned_data) question.save() return question
def add_a_question(): # Gets data from the client body = request.get_json() # retrieves search term from the frontend search_term = body.get('searchTerm') ''' Checks for searchterm to ascertain what user is doing. a valid searchterm indicates a POST request for Searching question in the database ''' if search_term: search_term_formatted = "%{}%".format(search_term) # Query the database using the searhterm_formatted questions = Question.query\ .filter(Question.question.ilike(search_term_formatted)).all() current_questions = paginate_questions(request, questions) return jsonify({ "success": True, "questions": current_questions, "total_questions": len(questions) }) else: ''' In the absence of a searchterm, continue with adding a question to the db ''' new_question = body.get('question') new_answer = body.get('answer') new_category = body.get('category') new_difficulty = body.get('difficulty') if not (new_question and new_answer and new_category and new_difficulty): abort(400) # lookup db to ensure no duplicate question check_question = Question.query\ .filter(Question.question == new_question)\ .filter(Question.category == new_category).one_or_none() if check_question is None: try: question = Question(question=new_question, answer=new_answer, category=new_category, difficulty=new_difficulty) question.insert() # update the frontend after adding a question successfully current_category = question.category categories = Category.query.order_by(Category.id).all() categories_ids = [category.id for category in categories] # paginate list of questions selection = Question.query\ .filter(Question.category == current_category)\ .order_by(Question.id).all() current_questions = paginate_questions(request, selection) return jsonify({ "success": True, "questions": current_questions, "total_questions": len(selection), "categories": categories_ids, "current_category": current_category, "created": question.id }), 201 except: abort(422) else: abort(422)
def questionnaire(request): ''' get:查询用户信息,填充表单中个人信息 post:查询用户,更新用户信息,计算分数,记录问卷和分数和时间 ''' personinfo_name = [ 'name', 'sex', 'age', 'adno', 'home', 'profession', 'education', 'disease_history', 'disease_age_h', 'disease_current', 'disease_age_c', 'used_drugs', 'using_drugs' ] try: person = Person.objects.get(username=request.user.username) except Person.DoesNotExist: person = None if request.method == "GET": if person: personinfo = person return render_to_response('questionnaire.html', locals()) elif request.method == "POST": personinfo = {'username': request.user.username} for name in personinfo_name: personinfo[name] = request.POST.get(name, '') if not person: person = Person(**personinfo) else: person = Person.objects.get(username=request.user.username) for key in personinfo_name: setattr(person, key, request.POST.get(key, '')) person.save() newquestion = Question( person=person, q1=int(request.POST.get('q1', '0')), q2=int(request.POST.get('q2', '0')), q3=int(request.POST.get('q3', '0')), q4=int(request.POST.get('q4', '0')), q6=int(request.POST.get('q6', '0')), q7=int(request.POST.get('q7', '0')), q8=int(request.POST.get('q8', '0')), q9=int(request.POST.get('q9', '0')), a=int(request.POST.get('a', '0')), b=int(request.POST.get('b', '0')), c=int(request.POST.get('c', '0')), d=int(request.POST.get('d', '0')), e=int(request.POST.get('e', '0')), f=int(request.POST.get('f', '0')), g=int(request.POST.get('g', '0')), h=int(request.POST.get('h', '0')), i=int(request.POST.get('i', '0')), j=int(request.POST.get('j', '0')), ) element_A = newquestion.q6 if newquestion.q2 <= 15: element_B = newquestion.a elif newquestion.q2 <= 30: element_B = 1 + newquestion.a elif newquestion.q2 <= 60: element_B = 2 + newquestion.a elif newquestion.q2 > 60: element_B = 3 + newquestion.a if newquestion.q4 > 7: element_C = 0 elif newquestion.q4 > 6: element_C = 1 elif newquestion.q4 >= 5: element_C = 2 elif newquestion.q4 < 5: element_C = 3 if newquestion.q3 > newquestion.q1: Sleep_efficiency = 1.0 * newquestion.q4 / (24 - newquestion.q3 + newquestion.q1) else: Sleep_efficiency = 1.0 * newquestion.q4 / (newquestion.q1 - newquestion.q3) if Sleep_efficiency > 0.85: element_D = 0 elif Sleep_efficiency > 0.75: element_D = 1 elif Sleep_efficiency >= 0.65: element_D = 2 elif Sleep_efficiency < 0.65: element_D = 3 Sleep_disorder = newquestion.b + newquestion.c + newquestion.d + newquestion.e + newquestion.f + newquestion.g + newquestion.h + newquestion.i + newquestion.j if Sleep_disorder == 0: element_E = 0 elif Sleep_disorder <= 9: element_E = 1 elif Sleep_disorder <= 18: element_E = 2 elif Sleep_disorder <= 27: element_E = 3 element_F = newquestion.q7 Daytime_dysfunction = newquestion.q8 + newquestion.q9 if Daytime_dysfunction == 0: element_G = 0 elif Daytime_dysfunction <= 2: element_G = 1 elif Daytime_dysfunction <= 4: element_G = 2 elif Daytime_dysfunction <= 6: element_G = 3 newquestion.score = element_A + element_B + element_C + element_D + element_E + element_F + element_G newquestion.time_submit = datetime.datetime.utcnow() newquestion.save() well = newquestion.score <= 7 return render_to_response('questionscore.html', locals())
def __init__(self, question_info_list): self.question_list = [ Question(question[1], question[2]) for question in question_info_list ]
def create_test_backup(request): test_obj = json.loads(request.body) test = Test() #import pdb; pdb.set_trace() if request.user.is_authenticated(): owner = User_Profile.objects.filter(user=request.user) test.owner = owner[0] test.test_name = test_obj['PRE_TEST']['test_name'] #test.subject = test_obj['PRE_TEST'].subject #test.target_exam = test_obj['PRE_TEST'].target_exam #test.topics = test_obj['PRE_TEST'].topics_included test.total_time = test_obj['PRE_TEST']['total_time'] test.pass_criteria = test_obj['PRE_TEST']['pass_criteria'] test.assoicated_class = Class.objects.get(pk=test_obj['CLASS_INFO']) test.save() try: for item in test_obj['QUESTIONS']: question = Question() question.question_text = item['question_text'] question.explanation = item['explanation'] question.options = json.dumps(item['options']) question.hint = item['hint'] question.difficulty = item['difficulty_level'] question.points = item['points'] question.owner = owner[0] #question.target_exam = test.target_exam #question.subject = test.subject #question.topic = item.topic question.save() test.questions.add(question) data = {"status": "success"} return JsonResponse(data) except Exception, e: raise e
def create_or_search_questions(): body = request.get_json() if not body: abort(400) search_term = body.get('searchTerm', None) if search_term: questions = Question.query.filter( Question.question.contains(search_term)).all() if not questions: abort(404) questions_found = [question.format() for question in questions] selections = Question.query.order_by(Question.id).all() categories = Category.query.all() categories_all = [category.format() for category in categories] return jsonify({ 'success': True, 'questions': questions_found, 'total_questions': len(selections), 'current_category': categories_all }) new_question = body.get('question', None) new_answer = body.get('answer', None) new_category = body.get('category', None) new_difficulty = body.get('difficulty', None) if not new_question: abort(400) if not new_answer: abort(400) if not new_category: abort(400) if not new_difficulty: abort(400) try: question = Question(question=new_question, answer=new_answer, category=new_category, difficulty=new_difficulty) question.insert() selections = Question.query.order_by(Question.id).all() questions_paginated = paginate_questions(request, selections) return jsonify({ 'success': True, 'created': question.id, 'questions': questions_paginated, 'total_questions': len(selections) }) except: abort(422)
def add(): ''' Handles POST requests for creating new questions and searching questions. ''' # load the request body body = request.get_json() # if search term is present if (body.get('searchTerm')): search_term = body.get('searchTerm') # query the database using search term selection = Question.query.filter( Question.question.ilike(f'%{search_term}%')).all() # 404 if no results found if (len(selection) == 0): abort(404) # paginate the results paginated = paginate_questions(request, selection) # return results return jsonify({ 'success': True, 'questions': paginated, 'total_questions': len(Question.query.all()) }) # if no search term, create new question else: # load data from body new_question = body.get('question') new_answer = body.get('answer') new_difficulty = body.get('difficulty') new_category = body.get('category') # ensure all fields have data if ((new_question is None) or (new_answer is None) or (new_difficulty is None) or (new_category is None)): abort(422) try: # create and insert new question question = Question(question=new_question, answer=new_answer, difficulty=new_difficulty, category=new_category) question.insert() # get all questions and paginate selection = Question.query.order_by(Question.id).all() current_questions = paginate_questions(request, selection) # return data to view return jsonify({ 'success': True, 'created': question.id, 'question_created': question.question, 'questions': current_questions, 'total_questions': len(Question.query.all()) }) except: # abort unprocessable if exception abort(422)
def create_question(): data = request.get_json() if not data: abort(400) if "searchTerm" in data: search_term = data.get("searchTerm", "") questions = Question.query.\ filter( Question.question.ilike(f"%{search_term}%") ).\ order_by(Question.id.asc()).\ all() formatted_questions = [ question.format() for question in questions ] return jsonify({ "success": True, "questions": formatted_questions, "total_questions": len(formatted_questions), "current_category": None }) else: validation_errors = validate_create_question_input(data) if validation_errors: return jsonify({ "success": False, "type": "invalid_request_error", "message": ( "The request could not be processed because" " of invalid data."), "validation_errors": validation_errors }), 400 category_id = data.get("category") category = Category.query.\ filter(Category.id == category_id).\ one_or_none() if not category: return jsonify({ "success": False, "type": "invalid_request_error", "message": ( "The request could not be processed because" " of invalid data."), "validation_errors": [ { "attribute": "category", "type": "not_found", "message": ( not_found_template.format( "category", category_id)) } ] }), 400 question = Question( question=data.get("question"), answer=data.get("answer"), category=data.get("category"), difficulty=data.get("difficulty") ) question.insert() return jsonify({ "success": True })
def save(self, user): question = Question(author=user, **self.cleaned_data) question.save() return question
def save(self): self.cleaned_data['author_id'] = self._user.pk question = Question(**self.cleaned_data) question.save() return question
class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_name = "trivia_test" self.database_path = "postgresql://{}/{}".format( 'localhost:5432', self.database_name) setup_db(self.app, self.database_path) self.new_question = Question( question='What is the diameter of the Earth?', answer='12,742 km', category='1', difficulty=5) # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() def tearDown(self): """Executed after reach test""" pass def test_get_categories(self): res = self.client().get('/categories') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertTrue(len(data['categories'])) def test_get_questions(self): res = self.client().get('/questions') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertEqual(data['currentCategory'], None) self.assertTrue(len(data['categories'])) self.assertTrue(len(data['questions'])) def test_404_questions_page_dne(self): res = self.client().get('/questions?page=1000') data = json.loads(res.data) self.assertEqual(res.status_code, 404) self.assertEqual(data['success'], False) self.assertEqual(data['message'], 'resource not found') def test_delete_question(self): newQuestion = self.new_question newQuestion.insert() res = self.client().delete('/questions/{}'.format(newQuestion.id)) data = json.loads(res.data) question = Question.query.filter( Question.id == newQuestion.id).one_or_none() self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertEqual(question, None) self.assertEqual(data['deleted'], newQuestion.id) self.assertTrue(len(data['questions'])) def test_422_deleting_question_dne(self): res = self.client().delete('/questions/123123') data = json.loads(res.data) self.assertEqual(res.status_code, 422) self.assertEqual(data['success'], False) self.assertEqual(data['message'], 'unprocessable') def test_new_question(self): res = self.client().post('/questions', json=self.new_question.format()) data = json.loads(res.data) self.assertEqual(data['success'], True) self.assertEqual(res.status_code, 200) self.assertTrue(data['created']) self.assertTrue(len(data['questions'])) def test_400_new_question_json_bad_format(self): res = self.client().post('/questions', json={'difficulty': 'blah'}) data = json.loads(res.data) self.assertEqual(res.status_code, 400) self.assertEqual(data['success'], False) self.assertEqual(data['message'], 'bad request') def test_search_question(self): res = self.client().post('/searchQuestions', json={'searchTerm': 'the'}) data = json.loads(res.data) self.assertEqual(data['success'], True) self.assertEqual(res.status_code, 200) self.assertTrue(len(data['questions'])) def test_questions_by_category(self): res = self.client().get('/categories/1/questions') data = json.loads(res.data) self.assertEqual(data['success'], True) self.assertEqual(res.status_code, 200) self.assertTrue(len(data['questions'])) self.assertTrue(data['total_questions']) self.assertEqual(data['currentCategory'], 1) def test_404_questions_by_categories_category_dne(self): res = self.client().get('/categories/1000/questions') data = json.loads(res.data) self.assertEqual(res.status_code, 404) self.assertEqual(data['success'], False) self.assertEqual(data['message'], 'resource not found') def test_get_quiz(self): res = self.client().post('/quizzes', json={ 'previous_questions': [13, 4], 'quiz_category': { 'id': 2 } }) data = json.loads(res.data) self.assertEqual(data['success'], True) self.assertEqual(res.status_code, 200) self.assertTrue(data['question']['id'] in data['previousQuestions']) self.assertTrue(data['question']) def test_400_quiz_json_bad_format(self): res = self.client().post('/quizzes', json={ 'previous_questions': [], 'quiz_category': { 'id': 'break' } }) data = json.loads(res.data) self.assertEqual(res.status_code, 400) self.assertEqual(data['success'], False) self.assertEqual(data['message'], 'bad request')
def extract_question(url,doc): """ DESC: to extract zhihu'question field Args: url: url must contains page num , #http://www.zhihu.com/question/20874376?sort=created&page=2 doc: xpath's object Return: None """ f = furl(url) page = f.args['page'] question_id = f.pathstr.split('/')[-1] if page == "1": title = doc.xpath('.//*[@id="zh-question-title"]/h2/span/text()')[0].strip() content = doc.xpath('.//div[@class="zh-summary summary clearfix"]')[0] content_text = content.text_content().strip() content = tostring(content,encoding='utf-8') comment_num = answer_num = 0 try: comment_num = doc.xpath('.//div[@id="zh-question-meta-wrap"]/div/a[@name="addcomment"]/text()') if len(comment_num_el): num_text = "".join(comment_num).strip() comment_num = num_re.search(num_text).group()[0] except: comment_num = 0 answer_num_el = doc.xpath('.//h3[@id="zh-question-answer-num"]') if len(answer_num_el): answer_num_el = answer_num_el[0] answer_num = answer_num_el.attrib['data-num'] q,created = Question.get_or_create(qid = question_id) q.title = title.strip() q.content = content.strip() q.content_text = content_text.strip() q.comment_num = comment_num q.answer_num = answer_num q.save() topic_list = doc.xpath('.//a[@class="zm-item-tag"]') for topic_a in topic_list: url = topic_a.attrib['href'] name = topic_a.text.strip() t_id = url.split('/')[-1] try: t,created = Topic.get_or_create(name=name.strip(),tid = t_id) Tq,created = TopicQuestion.get_or_create(tid = t_id,qid = question_id) except: pass page_list = doc.xpath('.//div[@class="question-page-pager"]//span/text()') page_num_set = set() for one in page_list: try: page_num = int(one) page_num_set.add(page_num) except ValueError: continue if page_num_set: max_page = max(page_num_set) if max_page>100: max_page = 100# limit comment page to 50 for one in range(2,max_page+1): f.args['page'] = one comment_page_list.append(f.url) if comment_page_list: for url in comment_page_list: rd.sadd(zhihu_url_key,url) answer_list = doc.xpath('.//div[@id="zh-question-answer-wrap"]/div[contains(@class,"zm-item-answer")]') for one in answer_list: a_id = one.attrib['data-atoken'] vote_num = one.xpath("./div/button/span[@class='count']/text()") if vote_num: vote_num = int(vote_num[0]) else: vote_num = 0 author_url = '' author = one.xpath('.//a[@class="author-link"]') if author: # false,anonymous user author_url = author[0].attrib['href'] content = one.xpath(".//div[contains(@class,'zm-editable-content')]")[0] content_text = one.xpath(".//div[contains(@class,'zm-editable-content')]")[0] content_text = content_text.text_content() content = tostring(content,encoding='utf-8') comment_num = 0 try: comment_num_el = one.xpath('.//div[@class="zm-meta-panel"]/a[@name="addcomment"]/text()') if len(comment_num_el): num_text = "".join(comment_num_el).strip() comment_num = num_re.search(num_text).group() except: pass date_element = one.xpath(".//div[@class='zm-meta-panel']/a[@itemprop='url']")[0] answer_url = date_element.attrib['href'] date_text = date_element.text for regex in DATE_REGEX: date_result = regex.search(date_text) if date_result: break if date_result: date_edit = to_legal_datetime(date_result) date_re = re.search("\d*-\d*-\d*",str(date_edit)) if date_re: date_edit = date_re.group() repetition_url = Answer.select().where(Answer.user_url == author_url) if repetition_url.count() == 0 : a,created = Answer.get_or_create(qid = question_id,aid=a_id) a.content = content.strip() a.edit_date = date_edit a.user_url = author_url or None a.vote = vote_num a.comment_num = comment_num a.content_text = content_text.strip() a.save() if author_url: rd.sadd(zhihu_url_key,author_url) else: logger.error("%s:url-repetition"%url)
def test_getQuestions_happy(self): self.category.insert() Question('test_question', 'test_answer', self.category.id, 5).insert() res = self.client.get('/api/v1/questions') self.assertEqual(res.status_code, 200)
class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_name = "triviatest" self.database_path = "postgresql://{}/{}".format( 'postgres:laug999@localhost:5432', self.database_name) setup_db(self.app, self.database_path) # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() def tearDown(self): """Executed after reach test""" pass """ TODO Write at least one test for each test for successful operation and for expected errors. """ def test_get_paginated_questions(self): res = self.client().get('/questions?page=1') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertTrue(data['total_questions']) self.assertTrue(len(data['questions'])) def test_404_request_beyond_valid_page(self): res = self.client().get('/questions?page=1000') data = json.loads(res.data) self.assertEqual(data['success'], False) self.assertEqual(res.status_code, 404) self.assertEqual(data['message'], 'resource not found') def test_get_questions_by_category(self): res = self.client().get('/categories/1/questions') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertTrue(data['total_questions']) self.assertTrue(len(data['questions'])) def test_404_request_beyond_valid_category(self): res = self.client().get('/categories/1000/questions') data = json.loads(res.data) self.assertEqual(data['success'], False) self.assertEqual(res.status_code, 404) self.assertEqual(data['message'], 'resource not found') def test_create_new_question(self): res = self.client().post('/questions', json={ "question": "from where?", "answer": "from test_flaskr", "category": "1", "difficulty": "2" }) data = json.loads(res.data) self.assertEqual(data['success'], True) self.assertEqual(data['Question added'], 'from where?') self.assertEqual(res.status_code, 200) def test_400_post_wrong_format_question(self): res = self.client().post('/questions', json={ "question": "from where?", "answer": "from test_flaskr", "cat": "1", "difficulty": "2" }) data = json.loads(res.data) self.assertEqual(res.status_code, 400) self.assertEqual(data['success'], False) self.assertEqual(data['message'], 'Bad Request') def test_422_delete_beyond_valid_questions(self): res = self.client().delete('/questions/1000') data = json.loads(res.data) self.assertEqual(res.status_code, 422) self.assertEqual(data['success'], False) self.assertEqual(data['message'], 'Unprocessable Entity') def test_delete_question(self): self.ques = 'What is my name?' self.answer = 'Meshal' self.category = 3 self.difficulty = 1 self.question = Question(self.ques, self.answer, self.category, self.difficulty) self.question.id = 100 self.question.insert() res = self.client().delete('/questions/100') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) def test_search_for_questions(self): res = self.client().post('/questions', json={'searchTerm': 'whose'}) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) def test_get_categories(self): res = self.client().get('/categories') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(len(data['categories']), 6) def test_get_quiz(self): res = self.client().post('/quizzes', json={ 'previous_questions': [], 'quiz_category': { "type": "Science", "id": "1" } }) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) def test_get_quez_with_all_in_previous_questions(self): total_no_questions = len(Question.query.all()) previous_questions = [] previous_questions.extend(range(0, total_no_questions)) res = self.client().post('/quizzes', json={ 'previous_questions': previous_questions, 'quiz_category': { "type": "Science", "id": "1" } }) data = json.loads(res.data) self.assertEqual(data['success'], False) self.assertEqual(res.status_code, 404) self.assertEqual(data['message'], 'resource not found')
def askquestion(request): """提问模板""" name = request.session.get("name") if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): data = form.cleaned_data title = data["title"] text = data["text"] qtype = data["q_type"] user = User.objects.get(name=name.split()[0]) questiontype = QuestionType(name=qtype) questiontype.save() question = Question(user=user, title=title, text=text, q_type=questiontype) question.save() # return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) return JsonResponse({"status": "ok"}) else: # return HttpResponse(request.POST.get('title')) return render(request, "askquestion.html") if name: access_key = "wmN715-Lo5SC1jYIkuqObCLl1bhZoURTxewUGyq2" secret_key = "IXXeA4-Rzu9RB6nkf687UjQt9YCOp1JpWptm0C0y" bucket_name = "iforj" q = qiniu.Auth(access_key, secret_key) token = q.upload_token(bucket_name) return render( request, "askquestion.html", {"QuestionForm": QuestionForm, "uptoken": token, "name": name.split()} ) else: return HttpResponseRedirect("/")
def upload_new_question(question_source, question, tags): new_question = Question(question = question, question_source=question_source) new_question.save() tags_final = [] for tag in tags: try: search_tag = Tag.objects.get(tag=tag) tags_final.append(search_tag) continue except Tag.DoesNotExist: new_tag = Tag(tag=tag) new_tag.save() tags_final.append(new_tag) continue continue for tag in tags_final: print tag.tag for tag in tags_final: tag.questions.append(new_question) tag.save() continue return new_question.id