Beispiel #1
0
def lesson_update(request, lesson_id):
    lesson = get_record_by_id(lesson_id, Lesson)

    json_data = json_from_request(request)

    if "name" in json_data.keys():
        if json_data['name'] != lesson.name:
            validate_lesson_name(name=json_data['name'],
                                 school_id=g.user.school_id)
            lesson.name = json_data['name']

    if "subject_id" in json_data.keys():
        subject = get_record_by_id(json_data['subject_id'],
                                   Subject,
                                   custom_not_found_error=CustomError(
                                       409, message="Invalid subject_id."))
        lesson.subject_id = subject.id

    if "teacher_ids" in json_data.keys():
        lesson.teachers = []
        add_teachers(json_data['teacher_ids'], lesson)

    if "student_ids" in json_data.keys():
        lesson.students = []
        add_students(json_data['student_ids'], lesson)

    db.session.add(lesson)
    db.session.commit()

    return jsonify({'success': True, 'message': 'Updated.'})
Beispiel #2
0
def create_quiz(request):
    top_level_expected_keys = [
        "lesson_id", "title", "description", "date_due", "questions"
    ]
    json_data = json_from_request(request)
    check_keys(top_level_expected_keys, json_data)

    # Validate lesson
    lesson = get_record_by_id(json_data['lesson_id'], Lesson)
    if g.user.id not in [t.id for t in lesson.teachers]:
        raise UnauthorizedError()

    # Validate date
    date_due_string = json_data['date_due']
    try:
        date_due = datetime.datetime.strptime(date_due_string,
                                              "%d/%m/%Y").date()
    except ValueError:
        raise CustomError(409,
                          message="Invalid date_due: {}.".format(
                              json_data['date_due']))

    quiz = Quiz(lesson_id=json_data['lesson_id'],
                title=json_data['title'],
                description=json_data['description'],
                date_due=date_due,
                number_of_questions=len(json_data['questions']))

    db.session.add(quiz)
    db.session.commit()

    for question_object in json_data['questions']:
        if 'answer' and 'question_text' not in question_object.keys():
            raise CustomError(
                409,
                message=
                "Invalid object in questions array. Make sure it has a question and a answer."
            )
        question = Question(quiz.id, question_object['question_text'],
                            question_object['answer'])
        db.session.add(question)
        quiz.questions.append(question)

    db.session.add(quiz)
    db.session.commit()
    return jsonify(quiz.to_dict()), 201
Beispiel #3
0
def add_teachers(teacher_ids, lesson):
    for teacher_id in teacher_ids:
        user = get_record_by_id(
            teacher_id,
            User,
            custom_not_found_error=CustomError(
                409,
                message="Invalid id in teacher_ids: {}".format(teacher_id)))
        #  TODO: Add role checking
        lesson.teachers.append(user)
Beispiel #4
0
def add_students(student_ids, lesson):
    for student_id in student_ids:
        user = get_record_by_id(
            student_id,
            User,
            custom_not_found_error=CustomError(
                409,
                message="Invalid id in student_ids: {}".format(student_id)))
        #  TODO: Add role checking
        lesson.students.append(user)
Beispiel #5
0
def create_essay(request):
    """Function to create an essay from request."""
    # List of keys needed to create an Essay
    top_level_expected_keys = [
        "lesson_id",
        "title",
        "description",
        "date_due",
    ]

    # Extract JSON from request and check keys are present
    json_data = json_from_request(request)
    check_keys(top_level_expected_keys, json_data)

    # Validate lesson
    lesson = get_record_by_id(json_data['lesson_id'], Lesson)
    if g.user.id not in [t.id for t in lesson.teachers]:
        raise UnauthorizedError()

    # Validate date
    date_due_string = json_data['date_due']
    try:
        date_due = datetime.datetime.strptime(date_due_string,
                                              "%d/%m/%Y").date()
    except ValueError:
        raise CustomError(409,
                          message="Invalid date_due: {}.".format(
                              json_data['date_due']))

    # Create Essay
    essay = Essay(
        lesson_id=json_data['lesson_id'],
        title=json_data['title'],
        description=json_data['description'],
        date_due=date_due,
    )

    db.session.add(essay)
    db.session.commit()

    return jsonify(essay.to_dict()), 201
Beispiel #6
0
def user_update(request, user_id):
    data = json_from_request(request)
    user = get_record_by_id(user_id, User)

    possible_keys = [
        "first_name", "last_name", "password", "username", "email", "form_id"
    ]
    check_values_not_blank(data.keys(), data)

    if "first_name" in data.keys():
        user.first_name = data['first_name']

    if "last_name" in data.keys():
        user.first_name = data['first_name']

    if "password" in data.keys():
        user.password = user.generate_password_hash(data['password'])

    if "email" in data.keys():
        if User.query.filter_by(email=data['email']).first() is not None:
            raise FieldInUseError("email")
        user.email = data['email']

    if "username" in data.keys():
        if User.query.filter_by(
                username=data['username'],
                school_id=g.user.school_id).first() is not None:
            raise FieldInUseError("username")
        user.username = data['username']

    if "form_id" in data.keys():
        # Validate form id
        form = get_record_by_id(data["form_id"],
                                Form,
                                custom_not_found_error=CustomError(
                                    409, message="Invalid form_id."))
        user.form_id = form.id

    db.session.add(user)
    db.session.commit()
    return jsonify({'success': True, 'message': 'Updated.'})
Beispiel #7
0
def lesson_create(request):
    # Parse JSON from request
    data = json_from_request(request)

    # Check JSON has keys needed
    expected_keys = ['name', 'subject_id']
    check_keys(expected_keys=expected_keys, data=data)

    # Validate subject_id
    subject = get_record_by_id(data['subject_id'],
                               Subject,
                               custom_not_found_error=CustomError(
                                   409, message="Invalid subject_id."))

    # Validate name
    validate_lesson_name(data['name'], g.user.school_id)

    # Create lesson
    lesson = Lesson(name=data['name'],
                    school_id=g.user.school_id,
                    subject_id=subject.id)

    # Add teachers (if supplied)
    if 'teacher_ids' in data.keys():
        add_teachers(data['teacher_ids'], lesson)

    # Add students (if supplied)
    if 'student_ids' in data.keys():
        add_students(data['student_ids'], lesson)

    db.session.add(lesson)
    db.session.commit()

    return jsonify({
        'success':
        True,
        'lesson':
        lesson.to_dict(nest_teachers=True, nest_students=True)
    }), 201
Beispiel #8
0
def user_create(request):
    #  Decode the JSON data
    data = json_from_request(request)

    # Validate data
    expected_keys = [
        "first_name", "last_name", "password", "username", "email"
    ]
    check_keys(expected_keys, data)
    check_values_not_blank(expected_keys, data)

    if User.query.filter_by(email=data['email']).first() is not None:
        raise FieldInUseError("email")

    if User.query.filter_by(username=data['username'],
                            school_id=g.user.school_id).first() is not None:
        raise FieldInUseError("username")

    # Create user
    user = User(first_name=data['first_name'],
                last_name=data['last_name'],
                email=data['email'],
                password=data['password'],
                username=data['username'],
                school_id=g.user.school_id)

    if "form_id" in data.keys():
        # Validate form id
        form = get_record_by_id(data["form_id"],
                                Form,
                                custom_not_found_error=CustomError(
                                    409, message="Invalid form_id."))
        user.form_id = form.id

    db.session.add(user)
    db.session.commit()

    return jsonify({"success": True, "user": user.to_dict()}), 201
Beispiel #9
0
        def decorated_function(*args, **kwargs):
            if g.user.has_permissions(permissions):
                return f(*args, **kwargs)

            raise CustomError(403)