def create_course(): if request.method == "POST": name = request.form.get('coursename') city = request.form.get('city') state = request.form.get('state') slope = request.form.get('slope') course = CourseModel(name, city, state, slope) if course.find_by_name(name): return {'message': f'A course named {name} already exists.'} course.save_to_db() distance_list = [] handicap_list = [] par_list = [] for i in range(1, 19): distance_str = "h" + str(i) + "d" handicap_str = "h" + str(i) + "h" par_str = "h" + str(i) + "p" distance_list.append(int(request.form.get(distance_str))) handicap_list.append(int(request.form.get(handicap_str))) par_list.append(int(request.form.get(par_str))) hole = HoleModel(course.id, i, par_list[i - 1], handicap_list[i - 1], distance_list[i - 1]) hole.save_to_db() course_dict = { 'name': name, 'city': city, 'state': state, 'slope': slope, 'distance': { 'hole_distances': distance_list, 'front_9_distance': sum(distance_list[:9]), 'back_9_distance': sum(distance_list[9:]), 'total_distance': sum(distance_list) }, 'handicap': { 'hole_handicaps': handicap_list, 'front_9_handicap': sum(handicap_list[:9]), 'back_9_handicap': sum(handicap_list[9:]), 'total_handicap': sum(handicap_list) }, 'par': { 'hole_pars': par_list, 'front_9_par': sum(par_list[:9]), 'back_9_par': sum(par_list[9:]), 'total_par': sum(par_list) } } return render_template('course_scorecard.jinja2', course_dict=course_dict) return render_template('blank_scorecard.jinja2')
def get(cls, name: str = None, course_id: int = None): course = CourseModel.find_by_name(name) if course_id: course = CourseModel.find_by_id(course_id) if course: return course_schema.dump(course), 200 if course: return {"course_intances": course_list_schema.dump(course)}, 200 return {"message": gettext("course_not_found")}, 404
def post(self, _id): data = Course.parser.parse_args() print(data) course = CourseModel(**data) try: course.save_to_db() except: return {"message": "An error occurred inserting the course."}, 500 return course.json(), 201
def loadJson(): dir_path = os.path.dirname(os.path.realpath(__file__)) file_path = dir_path + '\course.json' f = open(file_path) data = json.load(f) for obj in data: args = {'description': obj["description"], 'discount_price': obj["discount_price"], 'image_path': obj["image_path"], 'on_discount': obj["on_discount"], 'price': obj["price"], 'title': obj["title"]} course = CourseModel(**args) CourseModel.add_data_to_db(course) f.close()
def post(self): data = parser.parse_args() if CourseModel.query.filter_by(title=data['title']).first(): msg = "A course with title:'{}' already exists.".format( data['title']) return {"message": msg}, 400 course = CourseModel(**data) try: course.save() except: return {"message": "An error occurred while inserting Course"}, 500 return course.json(), 201
def delete(cls, course_id: int = None): course = CourseModel.find_by_id(course_id) if course: course.delete_from_db() return {"message": gettext("course_deleted")}, 200 return {"message": gettext("course_not_found")}, 404
def get(self, course_id): course = CourseModel.find_by_id(course_id) if course is None: return {"message": "Course not found."}, 404 return course.json(), 201
def delete(self, course_id): course = CourseModel.find_by_id(course_id) if course: course.delete_from_db() return { 'message': 'The course has been deleted from the database.' } return {'message': 'Course not found.'}, 404
def new_scorecard(): if request.method == "POST": name = request.form.get('course') return redirect(url_for('course_scorecard', name=name)) courses_list = [course for course in CourseModel.find_all()] return render_template('select_scorecard.jinja2', courses_list=courses_list)
def post(self): data = self.parser.parse_args() # course = CourseModel.find_by_email(data["email"]) # if course: # return {'message': "The email {} already exists.".format(data["email"])}, 400 valid_data = {key: val for key, val in data.items() if val is not None} course = CourseModel(**valid_data) try: course.save_to_db() except: return { "message": "An error occurred while saving to the database." }, 500 return course.json(), 201
def steps_count(course_id): course = CourseModel.find_by_id(course_id) steps_number = 0 for chapter in course.chapters: steps_number += 1 for quiz in course.quizzes: steps_number += 1 return steps_number
def post(self): data = Course.postparser.parse_args() classname = data['classname'] startdate = datetime.strptime(data['startdate'], "%Y-%m-%d") enddate = datetime.strptime(data['enddate'], "%Y-%m-%d") starttime = datetime.strptime(data['starttime'], "%I:%M %p") endtime = datetime.strptime(data['endtime'], "%I:%M %p") orgid = data['orgid'] userid = data['userid'] if data['classdays'] is None: classdays = [datetime.weekday(startdate)] else: classdays = list(map(int, data['classdays'].split(','))) jsonstr = [] msgstr = [] for n in range(int (((enddate + timedelta(days=1)) - startdate).days)): classdate = startdate + timedelta(n) day = datetime.weekday(classdate) if day in classdays: course = CourseModel(orgid=orgid, name=classname, starttime=datetime.strftime(starttime, "%H:%M"), endtime=datetime.strftime(endtime, "%H:%M"), classdate=datetime.strftime(classdate, "%Y-%m-%d"), startdate=datetime.strftime(startdate, "%Y-%m-%d"), enddate=datetime.strftime(enddate, "%Y-%m-%d"), classdays=data['classdays'] if data['classdays'] != None else datetime.weekday(startdate), userid=userid, requestuserid=None, requestdate=None, acceptuserid=None, acceptdate=None) try: course.save_to_db() msgstr.append({'status': "SUCCESS", "code": 200}) except: msgstr.append({'status': "ERROR", "code": 500}) jsonstr.append(course.json()) return {'courses': jsonstr,'messages': msgstr}
def delete(self): data = Course.getparser.parse_args() course = CourseModel.find_by_id(data['id']) msgstr = [] if course: course.delete_from_db() msgstr.append({'status': "SUCCESS", "code": 200, "message": "Course with ID {} deleted successfully!".format(data['id'])}) else: msgstr.append({'status': "ERROR", "code": 500, "message": "Course with ID {} not found!".format(data['id'])}) return {'messages': msgstr}
def delete(self, course_id): course = CourseModel.find_by_id(course_id) if course is None: return {"message": "Course not found."}, 404 try: course.delete() except: return {"message": "An error occurred while deleting Course."}, 500 return {"message": "Course deleted."}, 200
def put(self, _id): data = self.parser.parse_args() course = CourseModel.find_by_id(_id) if course: course.name = data["name"] course.category = data["category"] course.trainers = data["trainers"] course.description = data["description"] course.target_audience = data["target_audience"] course.outcomes = data["outcomes"] course.requirements = data["requirements"] course.start_date = date(*data["start_date"]) course.end_date = date(*data["end_date"]) course.total_lectures = data["total_lectures"] course.lectures_per_week = data["lectures_per_week"] course.lecture_duration = timedelta(*data["lecture_duration"]) course.min_spg = data["min_students_per_group"] course.max_spg = data["max_students_per_group"] else: valid_data = { key: val for key, val in data.items() if val is not None } course = CourseModel(**valid_data) try: course.save_to_db() except: return { "message": "An error occurred while saving to the database." }, 500 return course.json()
def update_steps_number(course_id): course = CourseModel.find_by_id(course_id) steps_number = 0 for chapter in course.chapters: steps_number += 1 for quiz in course.quizzes: steps_number += 1 for step in course.steps: step.final_step = steps_number db.session.commit()
def get(self): data = Course.getparser.parse_args() msgstr = [] if data['id'] is not None: course = CourseModel.find_by_id(data['id']) if course: msgstr.append({'status': "SUCCESS", "code": 200}) return {'courses': course.json(), 'messages': msgstr} msgstr.append({"status": "NULL", "code": 400, "message": "A course with ID '{}' was not found.".format(data['id'])}) elif data['userid'] is not None: courses = CourseModel.find_by_userid(data['userid'], data['allrequests']) if courses: msgstr.append({"status": "SUCCESS", "code": 200}) return {'courses': [course.json() for course in courses], 'messages': msgstr} if data['allrequests'] == None: msgstr.append({"status": "NULL", "code": 400, "message": "No courses for USERID '{}' were found.".format(data['userid'])}) else: msgstr.append({"status": "NULL", "code": 400, "message": "No sub requests found."}) else: msgstr.append({"status": "ERROR", "code": 400}) return {'messages': msgstr}
def get(self, search): search_list = search.split('_') # search query must be space separated query = {'term': 'term', 'subject': 'subject', 'code': 'code'} for elem in search_list: if elem[:2].isalpha() and elem[2:].isdigit(): query['term'] = "'" + elem[:2].upper() + elem[2:] + "'" if elem.isdigit(): query['code'] = "'" + elem + "'" if elem.isalpha() and 1 < len(elem) < 5: query['subject'] = "'" + elem.upper() + "'" course = CourseModel.find_by_course(query) if course['courses']: return course return {'message': 'Course not found'}, 404
def delete(self, _id): course = CourseModel.find_by_id(_id) if course: try: course.delete_from_db() except: return { "message": "An error occurred while deleting this course." }, 500 return {'message': 'Course deleted.'} return { 'message': "The course you're trying to delete doesn't exist." }, 400
def post(cls): data = request.get_json() course = CourseModel.find_by_id(data['course_id']) user = UserModel.find_by_id(data['user_id']) if user: if course: if user not in course.users: return {"message": gettext('user_not_enrolled')}, 400 else: course.disenroll_user(user) else: return {"message": gettext("course_not_found")}, 404 else: return {"message": gettext("user_not_found")}, 404 return {"message": gettext("user_disenrolled").format (course.name, week_list[course.day_week].capitalize() + course.start_time.strftime(' - %H:%M'))}, 200
def put(self): data = Course.putparser.parse_args() course = CourseModel.find_by_id(data['id']) jsonstr = [] msgstr = [] if course: if data['type'] == "confirmrequest": course.requestuserid = data['userid'] course.requestdate = datetime.today() course.save_to_db() if data['type'] == "cancelrequest": course.requestuserid = None course.requestdate = None course.acceptuserid = None course.acceptdate = None course.save_to_db() if data['type'] == "takeclass": course.acceptuserid = data['userid'] course.acceptdate = datetime.today() course.save_to_db() if data['type'] == "canceltake": course.acceptuserid = None course.acceptdate = None course.save_to_db() if data['type'] == "editclass": course.name = data['classname'] course.starttime = data['starttime'] course.endtime = data['endtime'] course.classdate = data['classdate'] course.save_to_db() msgstr.append({'status': "SUCCESS", "code": 200, "message": "Course with ID {} updated successfully!".format(data['id'])}) return {'courses': course.json(), 'messages': msgstr} else: msgstr.append({'status': "ERROR", "code": 500, "message": "Course with ID {} not found!".format(data['id'])}) return {'messages': msgstr}
def get(self): data = CourseListbyTitle.parser.parse_args() title_words = [] result = [] if data['title-words'] != None: title_words = data['title-words'].split(',') if len(title_words) > 0: course = CourseModel.find_by_title(title_words[0]) if course: return ({'courses': list(map(lambda x: x.json(), result))}) else: return { 'message': 'No Courses present matching those title keywords.' }, 404 else: return { 'courses': list(map(lambda x: x.json(), CourseModel.query.all())) } return {'message': 'No Courses present'}, 404
def post(self, name): if CourseModel.find_by_name(name): return { 'message': f"A course with name '{name}' is already entered into the database." }, 400 data = Course.parser.parse_args() course = CourseModel(name, **data) try: course.save_to_db() except: return { 'message': 'An error occurred inserting the course into the database.' }, 500 return course.json(), 201
def put(self, _id): data = Course.parser.parse_args() course = CourseModel.find_by_id(_id) if course: course.price = data['price'] course.description = data['description'] course.on_discount = data['on_discount'] course.title = data['title'] course.date_updated = datetime.datetime.utcnow() course.image_path = data['image_path'] else: course = CourseModel(**data) course.save_to_db() return course.json()
def put(self, course_id): data = parser.parse_args() course = CourseModel.find_by_id(course_id) if course is None: new_course = CourseModel(**data) try: new_course.save() except: return {"message": "An error occurred while inserting Course."}, 500 return new_course.json(), 201 try: course.update(**data) except: return {"message": "An error occurred while updating Course."}, 500 return course.json(), 200
def test_db(): from models.user import UserModel, RoleModel student = RoleModel('student') instructor = RoleModel('instructor') db.session.add_all([student, instructor]) db.session.commit() bart = UserModel('bart', 'bart', 'bart', 'student', firstname=None, lastname=None, picture=None) lisa = UserModel('lisa', 'lisa', 'lisa', 'student', firstname=None, lastname=None, picture=None) millhouse = UserModel('millhouse', 'millhouse', 'millhouse', 'student', firstname=None, lastname=None, picture=None) edna = UserModel('edna', 'edna', 'edna', 'instructor', firstname=None, lastname=None, picture=None) simour = UserModel('simour', 'simour', 'simour', 'instructor', firstname=None, lastname=None, picture=None) db.session.add_all([bart, lisa, millhouse, edna, simour]) db.session.commit() print('::: test roles and users ::: ok') ################### print('students') for student in student.users: print('>>> {}'.format(student.username)) print('instructors') for instructor in instructor.users: print('>>> {}'.format(instructor.username)) ################### from models.course import CourseModel from models.category import CategoryModel maths = CategoryModel('maths', fr_label=None, en_label=None, picture=None) english = CategoryModel('english', fr_label=None, en_label=None, picture=None) db.session.add_all([maths, english]) db.session.commit() math_course = CourseModel('mathematics', 'basic operations', simour.id, maths.id, picture=None) english_course = CourseModel('english', 'grammar', edna.id, english.id, picture=None) db.session.add_all([math_course, english_course]) db.session.commit() math_course.register_student(bart.id) math_course.register_student(lisa.id) english_course.register_student(lisa.id) english_course.register_student(millhouse.id) db.session.commit() print('::: test categories and courses ::: ok') ################### print('students enrolled in math') for student in math_course.students: print('>>> {}'.format(student.username)) print('author of math_course') print('>>> {}'.format(math_course.author.username)) print('edna published courses') for course in edna.published_courses: print('>>> {} - {}'.format(course.title, course.category.name)) ################### from models.chapter import ChapterModel from models.quiz import QuizModel from models.question import QuestionModel from models.answer import AnswerModel chapter1 = ChapterModel('adds', '2 + 2 = 4', 1, math_course.id) chapter2 = ChapterModel('subs', '2 - 2 = 0', 2, math_course.id) db.session.add_all([chapter1, chapter2]) db.session.commit() quiz1 = QuizModel('first grade', 1, math_course.id) quiz2 = QuizModel('second grade', 2, math_course.id) db.session.add(quiz1) db.session.add(quiz2) db.session.commit() question1 = QuestionModel('1 + 1?', 1, 2, quiz1.id) db.session.add(question1) db.session.commit() answer1 = AnswerModel('0', 1, question1.id) db.session.add(answer1) answer2 = AnswerModel('2', 2, question1.id) db.session.add(answer2) question2 = QuestionModel('3 - 1?', 2, 1, quiz1.id) db.session.add(question2) answer3 = AnswerModel('2', 1, question2.id) db.session.add(answer3) answer4 = AnswerModel('4', 2, question2.id) db.session.add(answer4) db.session.commit() print('::: test chapters and quizzes and questions and answers ::: ok') ################### print('chapters in math_course') for chapter in math_course.chapters: print('>>> {}'.format(chapter.title)) print('quizzes in math_course') for quiz in math_course.quizzes: print('>>> {}'.format(quiz.title)) print('questions in quiz1') for question in quiz1.questions: print('>>> {}'.format(question.question)) print('answers in question1') for answer in question1.answers: print('>>> {}'.format(answer.answer)) print('for question1 the good answer is number {}'.format( question1.good_answer)) current_question = question1.question good_answer = AnswerModel.query.filter_by( number=question1.good_answer).first() print('question: {} | response: {}'.format(current_question, good_answer.answer)) ################### from models.comment import CommentModel from models.rating import RatingModel comment1 = CommentModel('hay caramba', 'hay caramba', math_course.id, bart.id) comment2 = CommentModel('retention', 'retention', math_course.id, simour.id) comment3 = CommentModel('eat my short', 'eat my short', math_course.id, bart.id) db.session.add_all([comment1, comment2, comment3]) db.session.commit() rate1 = RatingModel(5, english_course.id, lisa.id) rate2 = RatingModel(3, english_course.id, millhouse.id) db.session.add_all([rate1, rate2]) db.session.commit() print('::: test comments and ratings ::: ok') ################### print('comments in math_course') for comment in math_course.comments: print('>>> {} by {}'.format(comment.title, comment.author.username)) print('ratings in english_course') for rate in english_course.ratings: print('>>> {}/5 by {}'.format(rate.rate, rate.author.username)) ################### from models.badge import BadgeModel from models.score import ScoreModel score = ScoreModel(2, 2, lisa.id, quiz1.id) db.session.add(score) db.session.commit() badge = BadgeModel('honor', math_course.id, lisa.id) db.session.add(badge) db.session.commit() print('::: test scores and badges ::: ok') ################### print('badges earned by lisa') for badge in lisa.badges: print('>>> {}'.format(badge.name)) print('scores in quiz1') for score in quiz1.scores: print('>>> {} by {}'.format(score.score, score.student.username))
def get(self, name): return { 'course': [course.json() for course in CourseModel.find_by_name(name)] }
def get(self): return { 'courses': [course.json() for course in CourseModel.find_all()] }
def get(self, name): course = CourseModel.find_by_name(name) if course: return course.json() return {'message': 'Course not found.'}, 404
def add_course(self, course_id): course = CourseModel.find_by_id(course_id) self.course = course