def validate(self, data): ''' Data validation :param data: data from post/put request :return: clean data ''' # move fields from orgExtra to data and rename fieldname from camelCase # to underscore for key, value in data['orgExtra'].items(): data[re.sub('([A-Z]+)', r'_\1', key).lower()] = value try: course_org, course_id, course_run = Exam.get_course_data( data['course_id']) except ValueError as e: raise serializers.ValidationError("Wrong courseId data") data['course_organization'] = course_org data['course_identify'] = "/".join((course_org, course_id)) data['course_run'] = "/".join((course_org, course_id, course_run)) data['exam_end_date'] = parser.parse(data['exam_end_date']) data['exam_start_date'] = parser.parse(data['exam_start_date']) del (data['orgExtra']) try: Exam(**data).full_clean() except ValidationError as e: raise serializers.ValidationError(e.message_dict) return super(ExamSerializer, self).validate(data)
def create_exam(user_id: UUID, user_role: Role, exam: schemas.Exam): is_authorized(user_role, "create_exam") exam_data = dict(name=exam.name, user=User[user_id]) if exam.video_tutorial_name: exam_data["video_tutorial_name"] = exam.video_tutorial_name return Exam(**exam_data)
def add_exam(): if current_identity.is_superuser: data = request.get_json() exam = Exam(data['subject_id'], data['exam_period_id'], data['date']) exam.save() return custom_response({'message': 'Successfully created'}, 201) else: return custom_response({'error': 'Unauthorized'}, 403)
def createNewExam(examName, groupName): groupObject = Group.objects.get(group_name=groupName) try: examObject = Exam.objects.get(group=groupObject, exam_name=examName) return False except Exam.DoesNotExist: examObject = Exam(group=groupObject, exam_name=examName) examObject.save() return True
def post(self, current_user: User): json = request.get_json(force=True) data, errors = exam_schema.load(json) if errors: return errors, 422 exam = Exam.query.filter_by(name=data['name']).first() if exam: return {'message': f'Exam name "{exam.name}" already exists'}, 400 data['date'] = datetime.now().strftime('%b %d, %Y') exam = Exam(data) db.session.add(exam) db.session.commit() exam = exam_schema.dump(exam).data return {'message': 'Exam succesfully created', 'exam': exam}, 201
def get_or_create_exam(db, items): exam = db.query(Exam).get(items['_id']) if exam is None: exam = Exam(id=items['_id'], **{ k: v for k, v in items.items() if k in ( "title", "level", "maximum_credits", "minimum_credits", "number", ) }) db.add(exam) db.commit() return exam
def post(self, request): """ Create exam record in database :param request: Key value pair data :return: status & respective message """ data = request.data if "college_ids" in data: college_ids = data["college_ids"] data.pop("college_ids") # Assuming field_id is mandatory as of now try: exam = Exam(**data) exam.save() LOGGER.info("exam created successfully") except Exception, error: LOGGER.error("Error:%s", str(error)) return Response({"status": "FAILED", "message": str(error)})
def get_exam(self): exam = self._get_old_in_time_exam() if exam: return self.exam_to_dict(exam) ids_query = select(el.explain.id for el in Exam) while True: try: query = Explain.select(lambda x: x.id not in ids_query) explain = self._get_query_random(query) sentence = self._get_query_random( Sentence.select(lambda x: x.explain == explain)) exam_query = Exam.select(lambda x: x.sentence == sentence) if exam_query.count(): exam = exam_query.first() exam.appear_cout += 1 else: exam = Exam(word=explain.word, explain=explain, sentence=sentence) return self.exam_to_dict(exam) except Exception: pass
def exam(): if(request.method == 'GET'): exams=Exam.query.all() exams_dict={} i = 0 for e in exams: exams_dict[str(i)] = str(e) i=i+1 print exams return jsonify(exams = exams_dict) #return "exams GET" else: if("firstName" in request.form and request.form["firstName"]): fn = request.form["firstName"] print fn else: fn = "Place" if("lastName" in request.form and request.form["lastName"]): ln = request.form["lastName"] else: ln = "Holder" if("exam_uuid" in request.form): exam_uuid = request.form["exam_uuid"] else: print "PROBLEM WITH EXAM UUID" exam_uuid = "666" if("date" in request.form): date = request.form["date"] print date else: date = "2000-01-01 11:11:11" try: if("phoneNumber" in request.form and request.form["phoneNumber"]): phoneNumber = request.form["phoneNumber"] print phoneNumber phoneNumber = re.sub(r'[^\w]','',phoneNumber) #phoneNumber = phoneNumber.translate(None,'()-') print phoneNumber else: phoneNumber = "4085291354" print phoneNumber except: print "Exception in PHONE NUMBER" print '-'*60 #print traceback.print_exc(file=sys.stdout) print traceback.print_exc() print '-'*60 d = datetime.strptime(date, "%Y-%m-%d %H:%M:%S") print d yyyymmddHHMM = d.strftime("%Y-%m-%d-%H-%M") print yyyymmddHHMM bucketName = (yyyymmddHHMM+"-"+exam_uuid).lower() print "BucketName " + bucketName val = doesBucketExist(s3connection,bucketName) if val is False: print "about to create bucket" createBucket(s3connection,bucketName) #include bucketName in Exam model exam = Exam.query.filter(Exam.uuid== exam_uuid).first() if not exam: exam = Exam(firstName=fn,lastName=ln,uuid=exam_uuid,bucket=bucketName, exam_date=d, phoneNumber = phoneNumber) db.session.add(exam) db.session.commit() try: examUploadConfirmation(exam_uuid,phoneNumber) except: print '-'*60 print "SOMETHING WRONG WITH TWILIO" print traceback.print_exc() print '-'*60 return jsonify(status="Exam Created") else: return jsonify(status="Exam was a duplicate and was not saved") else: return jsonify(status="Exam Bucket Already Created")
def test_exam_endpoints(self): user = rand.user() course = Course(name='World Lit') section1 = Section(name='Hour 1') section2 = Section(name='Hour 2') course.sections = [section1, section2] exam1 = Exam(name='Exam 1', exam_format='DDD..EEDD') exam2 = Exam(name='Exam 2', exam_format='..FFFFFFFFFFFF') course.exams = [exam1, exam2] user.courses.append(course) db.session.add(course) db.session.add_all([user, section1, section2, exam1, exam2]) db.session.commit() db.session.refresh(course) db.session.refresh(exam1) ############################################## # Verify that we have two exams in this course exams_list_response = self.client.get( '/api/course/{course_id}/exams'.format(course_id=course.id), headers={'Authorization': 'Bearer {}'.format(jwt_token)}) self.assertEqual(exams_list_response.status_code, HTTPStatus.OK) exam_list_data = json.loads(exams_list_response.data.decode()) self.assertEqual(len(exam_list_data['exams']), 2) ############################################### # Verify that a specific exam has the correct name and format self.assertIn('Exam 1', [exam['name'] for exam in exam_list_data['exams']]) self.assertNotIn('Exam Foo', [exam['name'] for exam in exam_list_data['exams']]) self.assertIn( 'DDD..EEDD', [exam['exam_format'] for exam in exam_list_data['exams']]) ############################################### # Add an Exam new_exam = Exam(name='Exam 3', exam_format='DDDDD') new_exam_request_response = self.client.post( '/api/course/{course_id}/exam/add'.format(course_id=course.id), data=json.dumps(new_exam.toJSON()), content_type='application/json', headers={'Authorization': 'Bearer {}'.format(jwt_token)}) self.assertEqual(new_exam_request_response.status_code, HTTPStatus.OK) exams_list_response = self.client.get( '/api/course/{course_id}/exams'.format(course_id=course.id), headers={'Authorization': 'Bearer {}'.format(jwt_token)}) exam_list_data = json.loads(exams_list_response.data.decode()) # we now have 3 exams self.assertEqual(len(exam_list_data['exams']), 3) new_exam_id = json.loads( new_exam_request_response.data.decode())['exam']['id'] ############################################### # Edit an exam update_exam_response = self.client.post( '/api/course/{course_id}/exam/{exam_id}/update'.format( course_id=course.id, exam_id=new_exam_id), data=json.dumps({ 'name': 'Exam 4', 'exam_format': 'CCC' }), content_type='application/json', headers={'Authorization': 'Bearer {}'.format(jwt_token)}) self.assertEqual(update_exam_response.status_code, HTTPStatus.OK) update_exam_response_data = json.loads( update_exam_response.data.decode()) self.assertEqual('CCC', update_exam_response_data['exam']['exam_format']) self.assertEqual('Exam 4', update_exam_response_data['exam']['name']) ############################################### # Delete an Exam delete_exam_response = self.client.delete( '/api/course/{course_id}/exam/{exam_id}'.format( course_id=course.id, exam_id=new_exam_id), headers={'Authorization': 'Bearer {}'.format(jwt_token)}) exams_list_response = self.client.get( '/api/course/{course_id}/exams'.format(course_id=course.id), headers={'Authorization': 'Bearer {}'.format(jwt_token)}) exam_list_data = json.loads(exams_list_response.data.decode()) # we should be back to two exams self.assertEqual(len(exam_list_data['exams']), 2) ############################################### ############################################### # Create three student exams for answers in ['DDDTTEEDD', 'ABCTFDEAC', 'DCBFFEAAA']: create_student_exam_response = self.client.post( '/api/course/{course_id}/exam/{exam_id}/student_exam'.format( course_id=course.id, exam_id=exam1.id), data=json.dumps({'answers': answers}), content_type='application/json', headers={'Authorization': 'Bearer {}'.format(jwt_token)}) exam1 = Exam.query.get( exam1.id ) # 'db.session.refresh' doesn't work here, as we're on to a different db session self.assertEqual(len(exam1.student_exams), 3) exam_response = self.client.get( '/api/course/{course_id}/exam/{exam_id}'.format( course_id=course.id, exam_id=exam1.id), headers={'Authorization': 'Bearer {}'.format(jwt_token)}) exam_response_data = json.loads(exam_response.data.decode()) self.assertEqual(len(exam_response_data['exam']['student_exams']), 3) ############################################### # Update one of those student exams student_exam_id = exam_response_data['exam']['student_exams'][0]['id'] self.client.post( '/api/course/{course_id}/exam/{exam_id}/student_exam/{student_exam_id}' .format(course_id=course.id, exam_id=exam1.id, student_exam_id=student_exam_id), data=json.dumps({'answers': 'AAAFFAAAA'}), content_type='application/json', headers={'Authorization': 'Bearer {}'.format(jwt_token)}) student_exam = StudentExam.query.get(student_exam_id) self.assertEqual(student_exam.answers, 'AAAFFAAAA') ############################################### # Delete a student exam delete_student_exam_response = self.client.delete( '/api/course/{course_id}/exam/{exam_id}/student_exam/{student_exam_id}' .format(course_id=course.id, exam_id=exam1.id, student_exam_id=student_exam_id), content_type='application/json', headers={'Authorization': 'Bearer {}'.format(jwt_token)}) exam1 = Exam.query.get(exam1.id) self.assertEqual(len(exam1.student_exams), 2)
def exam(update, context): reply = update.message.reply_text("¿De qué asignatura es el examen?") context.user_data['messages'] = [reply] context.user_data['event'] = Exam() return SUBJECT