Esempio n. 1
0
def user_stats():
    from rq import Queue
    from ..jobs import game_stats

    s3_bucket = current_app.config['S3_BUCKET']
    aws_region = current_app.config['AWS_REGION']

    q = Queue(connection=redis_store)

    user_role = ''
    if current_user.is_student():
        user_role = 'student'
    if current_user.is_teacher():
        user_role = 'teacher'
    if current_user.is_administrator():
        user_role = 'administrator'

    result = q.enqueue(game_stats.game_stats,
                       aws_region,
                       s3_bucket,
                       current_user.id,
                       user_role,
                       timeout=59 * 30)

    job_url = 'https://s3.amazonaws.com/{}/jobs/{}.csv'.format(
        s3_bucket, result.id)

    return render_template('game_stats.html', job_url=job_url)
Esempio n. 2
0
def archive_apply():
    form = ArchiveApplyForm()
    if form.apply.data:
        if not form.name.data or not form.student_id or not form.reason.data:
            flash('必须填写所有信息')
            return redirect(url_for('.archive_apply'))
        archive = Archive.query.filter_by(student_id=form.student_id.data)
        if archive.count() == 0:
            flash('查无此人档案')
            return redirect(url_for('.archive_apply'))
        elif current_user.is_student() and archive.first().student_id == current_user.student_id:
            flash('别试了,这种低级错误怎么会让你通过,不能借自己档案')
            return redirect(url_for('.archive_apply'))
        elif archive.first().name != form.name.data:
            flash('验证失败,请检查输入数据')
            return redirect(url_for('.archive_apply'))
        elif form.apply_type.data == 2 and archive.first().status == 0:
            flash('档案已被借出,暂不可实体借阅')
            return redirect(url_for('.archive_apply'))
        else:
            apply = Archive_Apply(
                date=datetime.utcnow(),
                applicant=current_user.id,
                student_id=form.student_id.data,
                apply_type=form.apply_type.data,
                describe=form.reason.data,
                status=0
            )
            db.session.add(apply)
            db.session.commit()
            flash('申请提交成功')
            return redirect(url_for('.person_archive_applys'))
    return render_template('Archive_Apply.html', form=form, select_main=2, select_second=2)
Esempio n. 3
0
def auth_login():
    if current_user.is_authenticated:
        return redirect(url_for("index"))

    if request.method == "GET":
        return render_template("auth/login.html", form=LoginForm())

    form = LoginForm(request.form)

    if not form.validate():
        return render_template("auth/login.html",
                               form=form,
                               error="Remember to fill all the fields")

    user = User.query.filter_by(email=form.email.data,
                                password=form.password.data).first()

    if not user:
        return render_template("auth/login.html",
                               form=form,
                               error="Incorrect email address or password")

    login_user(user)

    app.jinja_env.globals.update(is_student=current_user.is_student())
    app.jinja_env.globals.update(is_teacher=current_user.is_teacher())

    return redirect(url_for("index"))
Esempio n. 4
0
def is_student():
    if current_user:
        student = current_user.is_student()
        teacher = current_user.is_teacher()
        app.jinja_env.globals.update(is_student=student)
        app.jinja_env.globals.update(is_teacher=teacher)
        return
    else:
        app.jinja_env.globals.update(is_student=False)
        app.jinja_env.globals.update(is_teacher=False)
        return
Esempio n. 5
0
def get_redirect_url(student_profile_id):
    if (current_user.is_student()
            and current_user.student_profile_id == student_profile_id):
        return url_for('student.view_user_profile')
    else:
        if (current_user.is_counselor() or current_user.is_admin()):
            student = User.query.filter_by(
                student_profile_id=student_profile_id).first()
            if student is not None:
                return url_for(
                    'counselor.view_user_profile', user_id=student.id)
    return abort(404)
Esempio n. 6
0
def archive_info(student_id):
    if current_user.is_people() or (current_user.is_student() and current_user.student_id != student_id):
        abort(403)
    form = ArchiveInfoForm()
    archive = Archive.query.filter_by(student_id=student_id).first()
    path = '/home/liuyu/PycharmProjects/archives_management_system/app/static/images/' + str(
        student_id) + '.jpg'
    if os.path.exists(path):
        dir = 'images/' + str(student_id) + '.jpg'
    else:
        dir = 'images/profile_big.jpg'
    return render_template('Archive_profile.html', archive=archive, dir=dir, form=form, select_main=2, select_second=1)
Esempio n. 7
0
def rso_join(rid):
    if not current_user.is_student():
        abort(403)

    c = db.cursor()
    c.execute("INSERT INTO RSOMembers(username, rid)"
              "VALUES (%s, %s)", (current_user.username, rid))

    warns = c.fetchwarnings()
    if not warns:
        db.commit()
    else:
        print(warns)

    return redirect("/rso/{}".format(rid))
Esempio n. 8
0
def index():
    #render a different page based on each user_type
    if current_user.is_admin():
        return redirect(url_for('admin'))
    elif current_user.is_teacher():
        return redirect(url_for('teacher'))
    elif current_user.is_parent():
        return redirect(url_for('parent'))
    elif current_user.is_student():
        return redirect(url_for('student'))
    else:  #This should only happen if the user_type isn't set properly
        return render_template('index.html',
                               title="Home",
                               user=current_user,
                               upcoming=upcoming)
Esempio n. 9
0
    def index():
        cursor = get_db().cursor()

        if current_user.is_authenticated:
            if current_user.is_student():
                lesson_instances = get_lesson_instances_for_student_id(
                    current_user.student_id)
                return render_template('index.html',
                                       lesson_instances=lesson_instances)
            elif current_user.is_teacher():
                lesson_instances = get_lesson_instances_for_teacher_id(
                    current_user.teacher_id)
                return render_template('index.html',
                                       lesson_instances=lesson_instances)

        return render_template('index.html')
Esempio n. 10
0
def student(survey_id):
    # neccessary instance for survey creation
    s = Survey()
    res = Respond()
    error = None
    if current_user.is_admin() or current_user.is_staff():
        # the Admin and staff can preview the survey
        pass
    elif res.is_submitted(survey_id, current_user.get_id()) or \
    not (current_user.is_student() or current_user.is_guest()):
        return redirect(url_for("permission_deny"))

    # get the basic information for this survey_id
    this_survey = s.id_filter(survey_id).one()
    qids = s.get_qids(survey_id)
    if request.method == "POST":
        answerlist = []
        for qid in qids:
            try:
                # get all the answer form student
                # because the questoin_id in survey is start form 1
                # so add 1 in i and find the answer
                this_q = request.form[str(qid)]
                if not this_q:
                    error = "You must finish all the questions."
                answerlist.append(this_q)
            except:
                error = "You must finish all the questions."
        if not error:
            # push the recorded answers to database
            res.new_res(survey_id, current_user.get_id(), answerlist)
            return render_template("finish_survey.html")
    # get the question information form here
    q = Question()
    # all the question is here
    q_list = q.find_q(qids)


    return render_template("student.html", \
            course_name = this_survey[1]+" "+this_survey[2],\
            msg_err = error,\
            quest_list = q_list)
Esempio n. 11
0
def post_survey(survey_id):
    if current_user.is_student():
        return redirect(url_for("permission_deny"))

    s = Survey()
    if current_user.is_admin():
        # admin want to post the survey to staff
        s.post(survey_id)
    elif current_user.is_staff():
        # staff try to post this survey to student
        if s.is_premitted(survey_id, current_user.get_id()):
            # the staff is in that course
            s.review(survey_id)
        else:
            # the staff have no right to change the code
            return redirect(url_for("permission_deny"))
    # give a pront to show the successful message
    return render_template("msg.html",title= "Successfully Post a Survey",\
                msg_suc_l=["Successful Post a Survey",\
                "You were successfully posted survey "+str(survey_id)+".",\
                url_for("dashboard"),"Review More"])
Esempio n. 12
0
def dashboard():

    # route by the current user type
    c = Course()
    # get the survey instance
    s = Survey()

    # muti type of user respond
    if current_user.is_student():
        return render_template('dash/student.html',\
                survey_l = s.get_survey_by_user(current_user.uid))
    if current_user.is_staff():
        return render_template('dash/staff.html',\
                survey_l = s.get_survey_by_user(current_user.uid))
    if current_user.is_admin():
        # get all the ongoning survey and all the courses
        return render_template('dash/admin.html',survey_l = s.get_survey(),\
                course_l= c.get_course(),guest_l = UserData().show_unguest(),\
                enrol_l = EnrolRequest().get_requests())
    if current_user.is_guest():
        return render_template('dash/guest.html',\
                    survey_l = s.get_survey_by_user(current_user.uid),\
                    course_l= c.get_course())
Esempio n. 13
0
 def wrap_func(*args, **kwargs):
     if not current_user.is_student():
         return None
     return func(*args, **kwargs)
Esempio n. 14
0
def all_quizzes_take(qid):
    '''
    This is the route that will determine whether the student is taking the 
    quiz for the first time, or is coming back to view peers' feedback.
    '''
    if not current_user.is_student():
        if request.json:
            response = ({
                "message": "You are not allowed to take quizzes"
            }, 403, {
                "Content-Type": "application/json"
            })
            return make_response(response)
        else:
            flash("You are not allowed to take quizzes", "postError"
                  )  #FIXME this error category probably needs to change
            return redirect(url_for('pages.index'))

    quiz = models.Quiz.query.get_or_404(qid)

    sid = current_user.id  #FIXME need to use student ID too

    # TODO implement logic for deadlines
    # IF date <= DL1 THEN step #1 ELSE IF DL1 < date <= DL2 && previous attempt exists THEN step #2

    attempt = models.QuizAttempt.query.filter_by(quiz_id=qid).filter_by(
        student_id=sid).first()
    # FIXME we are taking the first... would be better to ensure uniqueness

    step1 = False
    step2 = False

    # NOTE old way to determine our step
    ## Is the student POSTing initial answer (step 1) or revised answers (step 2)
    ##if attempt is None:
    ##    step1 = True
    ##else:
    ##    step2 = True

    # new way to do so
    if quiz.status == "HIDDEN":
        response = ({
            "message": "Quiz not accessible at this time"
        }, 403, {
            "Content-Type": "application/json"
        })
        return make_response(response)

    step1 = (quiz.status == "STEP1" and attempt is None)
    step2 = (quiz.status == "STEP2" and attempt is not None)

    # sanity check
    if step1 == step2:
        # we have an issue, either the student should be taking simultaneously the two steps of the
        # quiz, which would be a BUG or they should take none, which most likely means the quiz is not yet available
        response = ({
            "message": "Quiz not accessible at this time"
        }, 403, {
            "Content-Type": "application/json"
        })
        #NOTE 403 is better here than 401 (unauthorized) here since there is no issue w/ auth
        return make_response(response)

    if request.method == 'GET':

        if step1:
            return jsonify(quiz.dump_as_dict())
        else:  #step2
            #TODO need to also return the answers + justifications of 2 peers
            #TODO what do we do if n peers answers are not available? with n+1 being # options for MCQ
            # That should not happen if we enforce due dates for review to be past due dates for quiz
            return jsonify(quiz.dump_as_dict())

    else:  #request.method == 'POST'
        #TODO sanity check
        # if len(responses) == len(justifications) == len(quiz.quiz_questions)

        if not request.json:
            abort(406, "JSON format required for request")  # not acceptable

        if step1:
            # validate that all required information was sent
            # BUG if the keys are missing we crash
            if request.json['initial_responses'] is None or request.json[
                    'justifications'] is None:
                abort(400, "Unable to submit quiz response due to missing data"
                      )  # bad request

            # Being in step 1 means that the quiz has not been already attempted
            # i.e., QuizAttempt object for this quiz & student combination does not already exist
            if attempt is not None:  # NOTE should never happen
                abort(
                    400,
                    "Unable to submit quiz, already existing attempt previously submitted"
                )  # bad request

            # so we make a brand new one!
            attempt = models.QuizAttempt(quiz_id=quiz.id, student_id=sid)

            # extract from request the dictionary of question_id : distractor_ID (or None if correct answer)
            initial_responses_dict = request.json['initial_responses']

            # we save a string version of this data in the proper field
            attempt.initial_responses = str(initial_responses_dict)  ###
            # we compute a dictionary of question_id : score in which score is 0 or 1
            #   1 means the student selected the solution (None shows in the responses)
            #   0 means the student selected one of the distractors (its ID shows in the responses)
            initial_scores_dict = {}
            # we also save the total score as we go
            attempt.initial_total_score = 0
            for key in initial_responses_dict:
                if int(initial_responses_dict[key]) < 0:
                    result = 1
                else:
                    result = 0
                initial_scores_dict[key] = result
                attempt.initial_total_score += result
            attempt.initial_scores = str(initial_scores_dict)

            # extract same structure here; question_id : justification string
            justifications_dict = request.json['justifications']
            attempt.justifications = str(justifications_dict)

            # Record in DB the justification with quizquestion id + distractor id + student ID--> justifications
            for key_quest in justifications_dict:
                quest = justifications_dict[key_quest]
                for key_just in quest:
                    just = models.Justification(quiz_question_id=key_quest,
                                                distractor_id=key_just,
                                                student_id=sid,
                                                justification=sanitize(
                                                    quest[key_just]))
                    models.DB.session.add(just)

            models.DB.session.add(attempt)
            models.DB.session.commit()

            response = ({
                "message": "Quiz attempt recorded in database"
            }, 200, {
                "Content-Type": "application/json"
            })
            # NOTE see previous note about using 204 vs 200
            return make_response(response)

        else:  #step2
            # validate that all required information was sent
            if request.json['revised_responses'] is None:
                abort(400, "Unable to submit quiz again due to missing data"
                      )  # bad request

            if attempt is None:
                abort(404)

            #TODO only get answers to all questions; no justifications needed, regardless of quiz mode
            #       Select one of the two students whose answers + justifications were seen as the most useful
            #       Specify which of their justification was the most conductive to learning something.
            #       sounds like we're going to need to make the feedback another model connected 1-to-1
            #       between QuizAttempts

            # we update the existing attempt with step 2 information
            revised_responses_dict = request.json['revised_responses']
            revised_scores_dict = {}
            attempt.revised_responses = str(revised_responses_dict)
            # we also save the total score as we go
            attempt.revised_total_score = 0
            for key in revised_responses_dict:
                if int(revised_responses_dict[key]) < 0:
                    result = 1
                else:
                    result = 0
                revised_scores_dict[key] = result
                attempt.revised_total_score += result
            attempt.revised_scores = str(revised_scores_dict)

            models.DB.session.commit()

            response = ({
                "message":
                "Quiz answers updated & feeback recorded in database"
            }, 200, {
                "Content-Type": "application/json"
            })
            #NOTE see previous note about using 204 vs 200
            return make_response(response)
Esempio n. 15
0
def view_survey(survey_id=None):
    if current_user.is_student():
        return redirect(url_for("permission_deny"))

    q = Question()
    s = Survey()
    error = None

    if request.method == "POST":
        # request for changing
        selected_Qid = s.get_qids(survey_id)
        # record the mandertory question
        q_force = []

        if selected_Qid and current_user.is_staff():
            # in the staff, they only can choose not mendatory_q
            # filter out all the mandertory question
            q_force = q.find_q(q_id=selected_Qid, pool_id="0")
            # change the q_force to  normal type(ids) == str
            q_force = [str(this_q[0]) for this_q in q_force]
        # get all the selected question
        q_id = request.form.getlist("qid")
        # save the changes, by reconstruct the question list
        # merge two ids into one array
        q_id += q_force
        s.update_survey(survey_id, q_id)
        if not q_id:
            error = ["Survey Create Error: Not Sufficient Question",\
                    "Please select at least one question.",\
                    url_for("view_survey",survey_id= survey_id),\
                    "Continue Review This Survey"]

        if not error and request.form["submit_type"] == "save":
            # show the saved survey
            pass

        elif not error and request.form["submit_type"] == "post":
            #  post to next stage
            return redirect(url_for("post_survey", survey_id=survey_id))
    # find the specify survey by id
    this_survey = s.find("survey.id", survey_id).one()
    # find the selected question
    # change the type to match the filter
    selected_Qid = s.get_qids(survey_id)
    # get the survey status by indent
    survey_status = int(this_survey[6])

    if selected_Qid:
        # filter the selected question
        q_force = q.find_q(q_id=selected_Qid, pool_id="0")
        q_opt = q.find_q(q_id=selected_Qid, pool_id="1")
    else:
        # overwrite the qfind muti reaction
        q_force = []
        q_opt = []

    if current_user.is_admin():
        # have the right to edit all the added question
        return render_template("final_survey.html", course_name=this_survey[1],\
                    course_year = this_survey[2],\
                    mendatory_q = q.find_q(pool_id = "0"),list_type = ["check","check"],\
                    optional_q = q.find_q(pool_id = "1"),select_q = selected_Qid,\
                    survey_id = survey_id,msg_err_l = error,survey_status= survey_status)
    elif current_user.is_staff():
        # only have the right to review the question
        # find the course that has recorded in the survey
        return render_template("final_survey.html", course_name=this_survey[1],\
                    course_year = this_survey[2],\
                    mendatory_q = q_force,list_type = ["num","check"],\
                    optional_q = q.find_q(pool_id= "1"),select_q = selected_Qid,\
                    survey_id = survey_id,msg_err_l = error,survey_status= survey_status)