def on_get(self, req, resp, *args, **kwargs): super(ResourceCheckCorrectAnswer, self).on_get(req, resp, *args, **kwargs) # Recivimos un JSON del usuario con 2 parámetros # "question" : EL texto de la pregunta # "answer" : la respuesta que el usuario ha dado a la pregunta aux_question = Question() aux_question.question = req.media["question"] # Filtraremos la pregunta para tener su id real_question = self.db_session.query(Question).filter \ (aux_question.question == Question.question).one() aux_answer = Answer() aux_answer.answer = req.media["answer"] # Filtraremos la respuesta para tener su id real_answer = self.db_session.query(Answer).filter \ (aux_answer.answer == Answer.answer).one() # Finalmente filtraremos en la Asociacion para comprovar si es correcta query = self.db_session.query(AnswerQuestionAssiation).filter\ (real_question.id == AnswerQuestionAssiation.id_question, real_answer.id == AnswerQuestionAssiation.id_answer).one() print(query.is_correct) if query.is_correct: resp.media = "La Respuesta es Correcta" else: resp.media = "La Respuesta no es Correcta" resp.status = falcon.HTTP_200
def setUp(self): self.app = create_app(TestingConfig) self.client = self.app.test_client # seed data self.role = Role('general') self.role.insert() self.user = User('Ahmed', 'Hamed', '*****@*****.**', 'ahmedhrayyan', 'secret', self.role.id) self.user.insert() self.question = Question(self.user.id, 'Is sal the best QA engine') self.question.insert() self.answer = Answer(self.user.id, self.question.id, 'Yes it is') self.answer.insert() self.token = gen_token(self.app.config['SECRET_KEY'], self.user)
def get_questions_from_db(): engine = sqlalchemy.create_engine(DATABASE_URL_DOCKER) engine.connect() Session = sessionmaker(bind=engine) session = Session() is_exist = bool(session.query(Quiz) \ .filter(Quiz.name == 'First quiz') \ .first()) print(is_exist) if is_exist is False: questions = get_questions_from_yml('data.yml') quiz = Quiz(name='First quiz') session.add(quiz) for question in questions: new_question = Question(name=question['name'], quiz=quiz) session.add(new_question) for answer in question['answers']: if 'is_correct' in answer: new_answer = Answer(name=answer['name'], is_correct=answer['is_correct'], question=new_question) else: new_answer = Answer(name=answer['name'], is_correct=False, question=new_question) session.add(new_answer) session.commit() questions = session.query(Question.name, Question.id) \ .filter(Question.quiz_id == 1) \ .all() answers = session.query(Answer.name, Answer.is_correct, Answer.question_id) \ .join(Question) \ .filter(Question.quiz_id == 1) \ .all() answers = [i._asdict() for i in answers] questions = [i._asdict() for i in questions] print(answers) print(len(answers)) print(type(answers)) print(questions) print(len(questions)) print(type(questions)) for question in questions: question['answers'] = [] for answer in answers: if question['id'] == answer['question_id']: question['answers'].append(answer) print(questions) session.close() return questions
def on_post(self, req, resp, *args, **kwargs): super(ResourceAddQuestion, self).on_get(req, resp, *args, **kwargs) q = Question() try: try: q.question = req.media["question"] category = req.media["category"] if category not in [ i.value for i in CategoryEnum.__members__.values() ]: raise falcon.HTTPInvalidParam( messages.event_status_invalid, "category") q.category = category answers = req.media["answers"] self.db_session.add(q) for answer in answers: a = Answer() a.answer = answer["answer"] self.db_session.add(a) self.db_session.commit() s = AnswerQuestionAssiation() s.id_question = q.id s.id_answer = a.id if answer["is_correct"]: s.is_correct = True else: s.is_correct = False self.db_session.add(s) self.db_session.commit() except IntegrityError: raise falcon.HTTPBadRequest(description=messages.user_exists) except KeyError: raise falcon.HTTPBadRequest( description=messages.parameters_invalid) resp.status = falcon.HTTP_200
def post_question(): data = request.get_json() or [] if 'content' not in data: abort(400, 'content expected in request body') # sanitize input content = bleach.clean(data['content']) # supporting markdown content = markdown(content) # retrive user_id using username (which is stored in the stack by requires_auth decorator) username = _request_ctx_stack.top.curr_user['sub'] user_id = User.query.filter_by(username=username).with_entities( User.id).one().id new_question = Question(user_id, content) try: new_question.insert() except Exception: abort(422) return jsonify({'success': True, 'data': new_question.format()})
def get_question_and_agree(question_id, selector): try: question = Question() question.question_id = selector.xpath( '//div[@id="question_topic_editor"]/@data-id')[0] question.title = selector.xpath( '//div[@class="aw-mod-head"]/h1/text()')[0] question.people_id = selector.xpath( '//dd[@class="pull-left"]/a/@data-id')[0] task_filter('people', question.people_id) post_time_str = selector.xpath( '//div[@class="aw-question-detail-meta"]/div[1]/span[1]/text()' )[0].replace("发表时间 ", "") question.post_time = str2datetime(post_time_str) access_time_str = selector.xpath( '//div[@class="aw-side-bar-mod-body"]/ul/li[1]/span/text()')[0] question.access_time = str2datetime(access_time_str) question.read_num = selector.xpath( '//div[@class="aw-side-bar-mod-body"]/ul/li[2]/span/text()')[0] question.follow_num = selector.xpath( '//div[@class="aw-side-bar-mod-body"]/ul/li[3]/span/text()')[0] question.content = "".join( selector.xpath( '//div[contains(@class,"aw-question-detail-txt")]/text()')) CommonOper.add_one(question) CommonOper.add_filter_key("question_id", question_id) agrees = [] agree_list = selector.xpath( '//div[@class="aw-question-detail-meta"]/p[contains(@class,"aw-agree-by")]/a/@data-id' ) for p in agree_list: task_filter('people', p) agree = Agree() agree.question_id = question.question_id agree.people_id = p agrees.append(agree) CommonOper.add_all(agrees) except Exception as e: jsl_log.warning( "get question error,question_id:{},here are details {}".format( question_id, e))
def fill_db(op): session = Session(bind=op.get_bind()) is_exist = bool(session.query(Quiz) \ .filter(Quiz.name == 'First quiz') \ .first()) print(is_exist) if is_exist is False: questions = get_questions_from_yml('data.yml') quiz = Quiz(name='First quiz') session.add(quiz) for question in questions: new_question = Question(name=question['name'], quiz=quiz) session.add(new_question) for answer in question['answers']: if 'is_correct' in answer: new_answer = Answer(name=answer['name'], is_correct=answer['is_correct'], question=new_question) else: new_answer = Answer(name=answer['name'], is_correct=False, question=new_question) session.add(new_answer) session.commit() questions = session.query(Question.name, Question.id) \ .filter(Question.quiz_id == 1) \ .all() answers = session.query(Answer.name, Answer.is_correct, Answer.question_id) \ .join(Question) \ .filter(Question.quiz_id == 1) \ .all() answers = [i._asdict() for i in answers] questions = [i._asdict() for i in questions] for question in questions: question['answers'] = [] for answer in answers: if question['id'] == answer['question_id']: question['answers'].append(answer) session.close()
def get(self): path_to_file = SETTINGS['QUESTIONS_FILE'] if not path_to_file: abort(405) with Database(auto_commit=True) as db: with open(path_to_file, 'r') as csvfile: qcm = csv.DictReader(csvfile, delimiter=',', quotechar='"', restval=90) for question in qcm: question_already_here = db.query(Question).filter_by( name=question['Question']).first() if question_already_here: LOG.info('QUESTION ALREADY IN DB.... moving on') continue tmp_question = Question(question['Question']) # tmp_question = Question(question['Question'], question['Ressource'], QCM) db.add(tmp_question) return jsonify(loaded=True)
db_session.add(account) index += 1 db_session.commit() # -------------------- CREATE QUESTIONS -------------------- mylogger.info("Creating default questions from file...") filepath = '/app/dev/questions' with open(filepath) as fp: line = fp.readline() cnt = 1 q = None while line: l = line.split(":") if l[0] == "C": q = Question() q.category = str.strip(l[1]) elif l[0] == "Q": q.question = str.strip(l[1]) elif l[0] == "AF" or l[0] == "AT": q.owner_id = int(random.uniform(1, 20)) db_session.add(q) db_session.commit() a = Answer() a.answer = str.strip(l[1]) db_session.add(a) db_session.commit() s = AnswerQuestionAssiation() s.id_question = q.id s.id_answer = a.id
account.set_password("0000") db_session.add(account) index += 1 db_session.commit() # -------------------- CREATE QUESTIONS -------------------- mylogger.info("Creating default questions from file...") filepath = '/app/dev/questions' with open(filepath) as fp: line = fp.readline() cnt = 1 q = None while line: l = line.split(":") if l[0] == "C": q = Question() q.category = str.strip(l[1]) elif l[0] == "Q": q.question = str.strip(l[1]) elif l[0] == "AF" or l[0] == "AT": db_session.add(q) db_session.commit() a = Answer() a.answer = str.strip(l[1]) db_session.add(a) db_session.commit() s = AnswerQuestionAssiation() s.id_question = q.id s.id_answer = a.id if l[0] == "AT":
class SalTestCase(unittest.TestCase): def setUp(self): self.app = create_app(TestingConfig) self.client = self.app.test_client # seed data self.role = Role('general') self.role.insert() self.user = User('Ahmed', 'Hamed', '*****@*****.**', 'ahmedhrayyan', 'secret', self.role.id) self.user.insert() self.question = Question(self.user.id, 'Is sal the best QA engine') self.question.insert() self.answer = Answer(self.user.id, self.question.id, 'Yes it is') self.answer.insert() self.token = gen_token(self.app.config['SECRET_KEY'], self.user) def tearDown(self): db.drop_all() def test_422_upload(self): res = self.client().post('api/upload', headers={ 'Authorization': 'Bearer %s' % self.token }, data={'file': (BytesIO(b'IMAGE DATA'), 'file.jpg')}) # fake data json_data = res.get_json() self.assertEqual(res.status_code, 422) self.assertFalse(json_data['success']) self.assertTrue(json_data['message']) def test_404_view_uploaded(self): res = self.client().get('/uploads/x') self.assertEqual(res.status_code, 404) def test_422_register(self): res = self.client().post('/api/register', json={ 'first_name': 'ahmed', 'last_name': 'hamed', 'email': '*****@*****.**', 'username': self.user.username, # username already exists 'password': '******' }) res_data = res.get_json() self.assertEqual(res.status_code, 422) self.assertFalse(res_data['success']) self.assertTrue(res_data['message']) def test_register(self): res = self.client().post('/api/register', json={ 'first_name': 'ahmed', 'last_name': 'hamed', 'email': '*****@*****.**', 'username': '******', 'password': '******' }) res_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(res_data['success']) self.assertEqual(res_data['data']['username'], 'test') def test_patch_user(self): res = self.client().patch('/api/user', headers={ 'Authorization': 'Bearer %s' % self.token }, json={ 'job': 'test', }) res_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(res_data['success']) self.assertEqual(res_data['data']['job'], 'test') def test_422_login(self): res = self.client().post('/api/login', json={ 'username': '******', 'password': '******' }) res_data = res.get_json() self.assertEqual(res.status_code, 422) self.assertFalse(res_data['success']) self.assertTrue(res_data['message']) def test_login(self): res = self.client().post('/api/login', json={ 'username': '******', 'password': '******' }) res_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(res_data['success']) self.assertEqual(res_data['data']['username'], 'ahmedhrayyan') def test_get_notifications(self): res = self.client().get('/api/notifications', headers={ 'Authorization': 'Bearer %s' % self.token }) res_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(res_data['success']) self.assertGreaterEqual(res_data['unread_count'], 0) def test_get_questions(self): res = self.client().get('/api/questions') json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) def test_404_show_question(self): res = self.client().get('/api/questions/232482') json_data = res.get_json() self.assertEqual(res.status_code, 404) self.assertFalse(json_data['success']) self.assertTrue(json_data['message']) def test_show_question(self): res = self.client().get('/api/questions/%i' % self.question.id) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) self.assertEqual(self.question.id, json_data['data']['id']) def test_400_post_question(self): res = self.client().post('/api/questions', headers={ 'Authorization': 'Bearer %s' % self.token }) json_data = res.get_json() self.assertEqual(res.status_code, 400) self.assertFalse(json_data['success']) self.assertTrue(json_data['message']) def test_post_question(self): content = 'Is this great or what' res = self.client().post('/api/questions', headers={ 'Authorization': 'Bearer %s' % self.token }, json={ 'user_id': self.user.id, 'content': content }) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) self.assertIn(content, json_data['data']['content']) def test_patch_question(self): res = self.client().patch('/api/questions/%i' % self.question.id, headers={ 'Authorization': 'Bearer %s' % self.token }, json={ 'accepted_answer': self.answer.id }) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) self.assertEqual(self.answer.id, json_data['data']['accepted_answer']) def test_404_delete_question(self): res = self.client().delete('/api/questions/10000', headers={ 'Authorization': 'Bearer %s' % self.token }, ) json_data = res.get_json() self.assertEqual(res.status_code, 404) self.assertFalse(json_data['success']) self.assertTrue(json_data['message']) def test_delete_question(self): res = self.client().delete('/api/questions/%i' % self.question.id, headers={ 'Authorization': 'Bearer %s' % self.token }, ) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) self.assertEqual(self.question.id, json_data['deleted_id']) def test_404_show_answer(self): res = self.client().get('/api/answers/10420') json_data = res.get_json() self.assertEqual(res.status_code, 404) self.assertFalse(json_data['success']) self.assertTrue(json_data['message']) def test_show_answer(self): res = self.client().get('/api/answers/%i' % self.answer.id) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) self.assertEqual(self.answer.id, json_data['data']['id']) def test_400_post_answer(self): res = self.client().post('/api/answers', headers={ 'Authorization': 'Bearer %s' % self.token }, content_type='application/json') json_data = res.get_json() self.assertEqual(res.status_code, 400) self.assertFalse(json_data['success']) self.assertTrue(json_data['message']) def test_post_answer(self): content = 'answer' res = self.client().post('/api/answers', headers={ 'Authorization': 'Bearer %s' % self.token }, json={ 'user_id': self.user.id, 'question_id': self.question.id, 'content': content }) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) self.assertIn(content, json_data['data']['content']) def test_patch_answer(self): content = 'new answer' res = self.client().patch('/api/answers/%i' % self.answer.id, headers={ 'Authorization': 'Bearer %s' % self.token }, json={ 'content': content }) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) self.assertIn(content, json_data['data']['content']) def test_404_delete_answer(self): res = self.client().delete('/api/answers/10000', headers={ 'Authorization': 'Bearer %s' % self.token }, ) json_data = res.get_json() self.assertEqual(res.status_code, 404) self.assertFalse(json_data['success']) self.assertTrue(json_data['message']) def test_delete_answer(self): res = self.client().delete('/api/answers/%i' % self.answer.id, headers={ 'Authorization': 'Bearer %s' % self.token }, ) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) self.assertEqual(self.answer.id, json_data['deleted_id']) def test_404_show_user(self): res = self.client().get('/api/users/x') json_data = res.get_json() self.assertEqual(res.status_code, 404) self.assertFalse(json_data['success']) self.assertTrue(json_data['message']) def test_show_user(self): res = self.client().get('/api/users/%s' % self.user.username) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) self.assertEqual(json_data['data']['username'], self.user.username) def test_404_get_user_questions(self): res = self.client().get('/api/users/x/questions') json_data = res.get_json() self.assertEqual(res.status_code, 404) self.assertFalse(json_data['success']) self.assertTrue(json_data['message']) def test_get_user_questions(self): res = self.client().get('/api/users/%s/questions' % self.user.username) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) def test_report_question(self): res = self.client().post('/api/report/question', headers={ 'Authorization': 'Bearer %s' % self.token }, json={ 'question_id': self.question.id }) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success']) def test_report_answer(self): res = self.client().post('/api/report/answer', headers={ 'Authorization': 'Bearer %s' % self.token }, json={ 'answer_id': self.answer.id }) json_data = res.get_json() self.assertEqual(res.status_code, 200) self.assertTrue(json_data['success'])
account.set_password("0000") db_session.add(account) index += 1 db_session.commit() # -------------------- CREATE QUESTIONS -------------------- mylogger.info("Creating default questions from file...") filepath = '/app/dev/questions' with open(filepath) as fp: line = fp.readline() cnt = 1 q = None while line: l = line.split(":") if l[0] == "C": q = Question() q.category = str.strip(l[1]) q.owners_id = 1 elif l[0] == "Q": q.question = str.strip(l[1]) elif l[0] == "AF" or l[0] == "AT": db_session.add(q) db_session.commit() a = Answer() a.answer = str.strip(l[1]) db_session.add(a) db_session.commit() s = AnswerQuestionAssiation() s.id_question = q.id s.id_answer = a.id