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 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 get_metadata(request, ef_id): """returns the metadata for a file""" ef = get_object_or_404(ExamFile, id=ef_id) try: e = Exam.objects.get(file=ef) except Exam.DoesNotExist: e = Exam() return HttpResponse(content=cjson.encode(e.serialize()), mimetype="application/json")
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 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 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_old_in_time_exam(self): now = datetime.datetime.now() before_now_5min = now - datetime.timedelta(minutes=5) before_now_1day = now - datetime.timedelta(days=1) query1 = Exam.select(lambda x: x.created_at <= before_now_5min and (x.mistake > 0 or x.appear_count == 1)) before_now_2day = now - datetime.timedelta(days=2) query2 = Exam.select(lambda x: before_now_2day <= x.created_at and x. created_at <= before_now_1day and (x.mistake > 0 or x.appear_count <= 2)) before_now_4day = now - datetime.timedelta(days=4) query3 = Exam.select(lambda x: before_now_4day <= x.created_at and x. created_at <= before_now_2day and (x.mistake > 0 or x.appear_count <= 3)) before_now_7day = now - datetime.timedelta(days=7) query4 = Exam.select(lambda x: before_now_7day <= x.created_at and x. created_at <= before_now_4day and (x.mistake > 0 or x.appear_count <= 4)) before_now_15day = now - datetime.timedelta(days=15) query5 = Exam.select(lambda x: before_now_15day <= x.created_at and x. created_at <= before_now_7day and (x.mistake > 0 or x.appear_count <= 5)) query6 = Exam.select(lambda x: before_now_15day > x.created_at and (x.mistake > 0 or x.appear_count <= 6)) query = query1 or query2 or query3 or query4 or query5 or query6 if query.count(): exam = self._get_query_random(query) exam.appear_count += 1 if exam.mistake: exam.mistake -= 1 commit() return exam
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 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_exam_performance(user_role: Role, exam_id: str): is_authorized(user_role, "get_exam_performance") exam = Exam.get(id=exam_id) if not exam: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Exam not found : id: {}".format(exam_id)) results = select(p for p in Performance if p.exam == exam)[:] performance = [] for result in results: performance.append(result.to_dict()) return performance
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 add_participant(user_id: UUID, user_role: Role, participant: schemas.Participant): is_authorized(user_role, "add_participant") exam_id = participant.exam_id learner_id = participant.user_id exam = Exam.get(id=exam_id, user=User[user_id]) if not exam: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Exam not found : id: {}".format(exam_id)) learner = User.get(id=learner_id, role=Role.learner) if not learner: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Learner not found : id: {}".format(learner_id)) participant = Participant(exam=exam, user=learner) return participant.to_dict()
def create_question(user_id: UUID, user_role: Role, question_in: schemas.Question): is_authorized(user_role, "create_question") exam = Exam.get(id=question_in.exam_id) if not exam: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Exam not found : id: {}".format( question_in.exam_id)) question = dict(text=question_in.text, marks=question_in.marks, exam=exam) if question_in.multi_choice: question["multi_choice"] = question_in.multi_choice if question_in.answer: question["answer"] = question_in.answer counter = select(max(q.number) for q in Question if q.exam == exam)[:][0] if not counter: counter = 0 question["number"] = counter + 1 return Question(**question).to_dict()
from datetime import datetime, timedelta import logging from models import Exam, Assignment from FCM import sendNotification from apiMethods import createNotification logging.basicConfig(level=logging.DEBUG) LOG = logging.getLogger(__name__) date = (datetime.now() + timedelta(days=7)) date = date.strftime('%d-%m-%Y') LOG.info(date) examList = Exam.query(Exam.dueDate == date).fetch() LOG.info(str(examList)) assignmentList = Assignment.query(Assignment.dueDate == date).fetch() for exam in examList: LOG.info(str(exam)) sendNotification(exam.courseId.urlsafe(), exam.key.urlsafe(), 'exam', 'Warning!!! Exam ahead', 'There is a exam next week') course = exam.courseId.get() title = course.courseName notificationText = 'There is a exam next week' createNotification(course.studentIds, title, notificationText, 'exam', exam.key.urlsafe(), course.key.urlsafe()) for assignment in assignmentList: LOG.info(str(assignment)) sendNotification(assignment.courseId.urlsafe(),
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
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 post_metadata(request, ef_id): ef = get_object_or_404(ExamFile, id=ef_id) try: e = Exam.objects.get(file=ef) except Exam.DoesNotExist: e = Exam() e.file = ef e.professor, c = Professor.objects.get_or_create(name=request.POST['professor']) e.subject, c = Subject.objects.get_or_create(name=request.POST['subject']) e.degree, c = Degree.objects.get_or_create(name=request.POST['degree']) try: e.year = int(request.POST['year']) except ValueError: r = HttpResponse("invalid year") r.status_code = 405 return r e.hws = True if request.POST['hws'] == "true" else False e.solution = True if request.POST['solution'] == "true" else False e.note = request.POST['note'] e.save() return HttpResponse("OK")
def increase_mistake(self, exam_id): exam = Exam.get(id=exam_id) exam.mistake += 1 commit() return exam