示例#1
0
 def post(self):
     data = request.json
     res = entities.check_token(request.headers["Authorization"])
     if res == None:
         raise Exception("invalid token")
     description = data["description"]
     is_global = bool(data["global"])
     _, group = res
     if group != entities.group_admin:
         return err.not_allow_error
     score_classification_obj = model.Score_classification(
         description=description, is_global=is_global, enabled=True)
     model.db.session.add(score_classification_obj)
     model.db.session.commit()
     return {"status": "success"}
示例#2
0
 def put(self):
     data = request.json
     res = entities.check_token(request.headers["Authorization"])
     if res == None:
         raise Exception("invalid token")
     id = data["id"]
     description = data["description"]
     is_global = data["global"]
     _, group = res
     if group != entities.group_admin:
         return err.not_allow_error
     score_classification_obj = model.Score_classification.query.get(id)
     score_classification_obj.description = description
     score_classification_obj.is_global = is_global
     model.db.session.commit()
     return {"status": "success"}
示例#3
0
 def post(self):
     res = entities.check_token(request.headers["Authorization"])
     if res == None:
         raise Exception("invalid token")
     user, group = res
     if group != entities.group_student:
         uuid = user
     else:
         stu_obj = model.Student.query.filter_by(username=user).first()
         uuid = stu_obj.project.uuid
     parser = reqparse.RequestParser()
     parser.add_argument(
         "file",
         type=werkzeug.datastructures.FileStorage,
         location="files",
         required=True,
     )
     parser.add_argument("type", required=True)
     args = parser.parse_args()
     f = args["file"]
     fn = f.filename
     if entities.filename_validation(fn) == False:
         return err.upload_error
     fn = entities.make_unique(fn)
     fn = werkzeug.utils.secure_filename(fn)
     folder = os.path.join(
         os.path.abspath(__file__ + "/.."),
         "../..",
         entities.config.upload_path,
         uuid,
     )
     if not os.path.exists(folder):
         os.mkdir(folder)
     path = os.path.join(folder, fn)
     f.save(path)
     fn = os.path.join(entities.config.url_prefix, f"./{uuid}/", fn)
     db_f = None
     if args["type"] == "file":
         db_f = model.File(location=fn)
     elif args["type"] == "image":
         db_f = model.Image(path=fn, description="")
     else:
         raise Exception("Type not define")
     model.db.session.add(db_f)
     model.db.session.commit()
     return {"status": "success", "link": fn}
示例#4
0
 def put(self, id=None, uuid=None):
     data = request.json
     res = entities.check_token(request.headers["Authorization"])
     if res == None:
         raise Exception("invalid token")
     data = data["data"]
     user, group = res
     if uuid != None:
         return err.not_allow_error
     elif id != None:
         if group == entities.group_teacher or group == entities.group_admin:
             pass
         elif model.Student.query.filter_by(
                 username=user).first().project_id != id:
             return err.not_allow_error
         result = model.Project.query.get(id)
         if result == None:
             return err.topic_not_found
         if group != entities.group_student:
             result.uuid = entities.normilize_uuid(data["uuid"])
         result.name = data["title"]
         result.keywords = [
             f"{entities.utf8_str_to_normal(k)}" for k in data["keywords"]
         ]
         result.motivation = data["description"]
         result.faqs = data["faqs"]
         result.videos_links = data["videos_links"]
         result.cover_img_id = entities.links_to_imgs([data["cover"]])[0]
         result.arch_imgs_id = entities.links_to_imgs(data["arch_imgs"])
         result.results_imgs_id = entities.links_to_imgs(
             data["results_imgs"])
         result.members_imgs_id = entities.links_to_imgs(
             data["members_imgs"])
         result.report_file_id = (entities.links_to_files(
             [data["report_file"]])[0] if data["report_file"] != "" else -1)
         result.presentation_file_id = (entities.links_to_files([
             data["presentation_file"]
         ])[0] if data["presentation_file"] != "" else -1)
         result.program_file_id = (entities.links_to_files([
             data["program_file"]
         ])[0] if data["program_file"] != "" else -1)
         model.db.session.commit()
         return {"status": "success"}
     else:
         return err.not_allow_error
示例#5
0
 def post(self):
     data = request.json
     res = entities.check_token(request.headers["Authorization"])
     if res == None:
         raise Exception("invalid token")
     changed = data["data"]
     _, group = res
     if group != entities.group_teacher:
         return err.not_allow_error
     for c in changed:
         if c["student_id"] != -1:
             student_id = int(c["student_id"])
             classification_id = int(c["classification_id"])
             score = float(c["score"])
             model.Score.query.filter_by(
                 student_id=student_id,
                 score_classification_id=classification_id).delete()
             new_score = model.Score(
                 student_id=student_id,
                 score_classification_id=classification_id,
                 score=score,
             )
             model.db.session.add(new_score)
             model.db.session.commit()
         elif c["uuid"] != -1:
             uuid = c["uuid"]
             classification_id = int(c["classification_id"])
             score = float(c["score"])
             project_id = model.Project.query.filter_by(
                 uuid=uuid).first().id
             model.Project_score.query.filter_by(
                 project_id=project_id,
                 score_classification_id=classification_id).delete()
             new_score = model.Project_score(
                 project_id=project_id,
                 score_classification_id=classification_id,
                 score=score,
             )
             model.db.session.add(new_score)
             model.db.session.commit()
         else:
             return err.not_allow_error
     return {"status": "success"}
示例#6
0
 def post(self, id=None, uuid=None):
     data = request.json
     res = entities.check_token(request.headers["Authorization"])
     if res == None:
         raise Exception("invalid token")
     data = data["data"]
     user, group = res
     if group != entities.group_student:
         return err.account_error
     if uuid != None or id != None:
         return err.not_allow_error
     stu = model.Student.query.filter_by(username=user).first()
     stu_class = stu.username[:-2]
     if stu.project_id != -1:
         return err.not_allow_error
     uuid = entities.normilize_uuid(data["uuid"])
     name = data["title"]
     if uuid == "" or name == "":
         return err.not_allow_error
     teacher = model.Teacher.query.filter_by(name=data["teacher"]).first()
     if teacher == None:
         return err.not_allow_error
     students = data["students"]
     teacher_id = teacher.id
     new_project = model.Project(
         uuid=uuid,
         name=name,
         teacher_id=teacher_id,
         year=int(stu_class[:-1]),
     )
     model.db.session.add(new_project)
     model.db.session.commit()
     print(new_project.id)
     for s in students:
         student = model.Student.query.get(s)
         student.project_id = new_project.id
         model.db.session.commit()
     return {"status": "success"}
示例#7
0
 def get(self):
     res = entities.check_token(request.headers["Authorization"])
     if res == None:
         raise Exception("invalid token")
     return {"status": "success"}
示例#8
0
 def get(self, id=None, uuid=None):
     if id != None:
         result = model.Project.query.get(id)
         if result == None:
             return err.topic_not_found
         return result.to_detail()
     elif uuid != None:
         result = model.Project.query.filter_by(
             uuid=entities.normilize_uuid(uuid)).first()
         if result == None:
             return err.topic_not_found
         return result.to_detail()
     else:
         parser = reqparse.RequestParser()
         parser.add_argument("random")
         parser.add_argument("highlight")
         parser.add_argument("keyword")
         parser.add_argument("year", type=int)
         parser.add_argument("search")
         parser.add_argument("token")
         args = parser.parse_args()
         if args["random"] != None:
             random_topics = (model.Project.query.filter(
                 ~model.Project.name.ilike(""),
                 ~model.Project.motivation.ilike(""),
             ).order_by(func.rand()).limit(12).all())
             return list(map(lambda x: x.to_simple(), random_topics))
         if args["highlight"] != None:
             highlight = (model.Project.query.filter(
                 ~model.Project.name.ilike(""),
                 ~model.Project.motivation.ilike(""),
                 model.Project.cover_img_id != 0,
             ).order_by(func.rand()).limit(5).all())
             return list(map(lambda x: x.to_simple(), highlight))
         if args["token"] != None:
             token = args["token"]
             res = entities.check_token(token)
             if res == None:
                 raise Exception("invalid token")
             user, group = res
             if group == entities.group_student:
                 stu_obj = model.Student.query.filter_by(
                     username=user).first()
                 return {"id": stu_obj.project_id}
             elif group == entities.group_teacher:
                 topics = model.Project.query.filter_by(
                     teacher_id=model.Teacher.query.filter_by(
                         username=user).first().id).all()
                 topics = entities.to_detail_obj_list(topics)
                 return topics
             else:
                 return err.not_allow_error
         # filters
         results = model.Project.query
         if args["keyword"] != None:
             word = args["keyword"]
             utf8_word = "".join(["\\\\u%04x" % (ord(c)) for c in word])
             results = results.filter(
                 model.db.or_(
                     model.Project.keywords.ilike(f"%{word}%"),
                     model.Project.keywords.ilike(f"%{utf8_word}%"),
                 ))
         if args["year"] != None:
             y = int(args["year"])
             results = results.filter_by(year=y)
         if args["search"] != None:
             text = str(args["search"])
             results = results.filter(
                 model.db.or_(
                     model.Project.uuid.ilike(f"{text}"),
                     model.Project.name.ilike(f"%{text}%"),
                     model.Project.motivation.ilike(f"%{text}%"),
                     model.Project.faqs.ilike(f"%{text}%"),
                 ))
         return entities.to_obj_list(results.all())
示例#9
0
    def post(self):
        res = entities.check_token(request.headers["Authorization"])
        if res == None:
            raise Exception("invalid token")
        _, group = res
        if group != entities.group_admin:
            return err.not_allow_error
        parser = reqparse.RequestParser()
        parser.add_argument("year", type=int, required=True)
        args = parser.parse_args()
        year = args["year"]
        students = model.Student.query.filter(
            model.Student.username.ilike(f"{year}%")).all()
        stu_obj = sorted(
            list(map(lambda x: x.to_detail_scores(), students)),
            key=lambda x: x["username"],
        )
        weight = entities.to_obj_list(
            model.Score_weight.query.filter_by(year=year))

        classification = entities.to_obj_list(
            model.Score_classification.query.filter_by(enabled=True))

        csv_header = (["組別編號", "班級", "座號", "姓名"] +
                      [i["description"]
                       for i in classification] + ["總成績", "指導老師"])

        csv_header_weight = (["權重", "", "", ""] + [
            list(
                filter(lambda x: x["score_classification_id"] == i["id"],
                       weight))[0]["weight"] for i in classification
        ] + ["", ""])

        csv_dir = "/tmp/"
        csv_file = f"{year}.csv"

        with open(f"{csv_dir}{csv_file}",
                  "w",
                  encoding="utf-8-sig",
                  newline="") as f:
            writer = csv.writer(f)
            writer.writerow(csv_header)
            writer.writerow(csv_header_weight)
            for stu in stu_obj:
                try:
                    project_id = stu["project_id"]
                    if project_id > 0:
                        project = entities.to_detail_obj_list(
                            model.Project.query.filter_by(id=project_id))[0]
                        uuid = project["uuid"]
                    else:
                        uuid = ""
                    _class = ""
                    if stu["username"][3] == "a":
                        _class = "甲班"
                    elif stu["username"][3] == "b":
                        _class = "乙班"
                    else:
                        _class = "綜高"
                    num = int(stu["username"][-2:])
                    name = stu["name"]
                    csv_data = [uuid, _class, num, name]

                    if uuid != "":
                        for i in classification:
                            score_obj = (project["score"]
                                         if i["global"] else stu["scores"])

                            __score = list(
                                filter(
                                    lambda x: x["score_classification_id"] ==
                                    i["id"],
                                    score_obj,
                                ))
                            if len(__score) > 0:
                                __score = __score[0]["score"]
                            else:
                                __score = 0
                            csv_data.append(__score)

                        bias = 4
                        adding = 0
                        sum_score = 0
                        sum_w = 0
                        for i, w in enumerate(csv_header_weight[4:-2]):
                            index = i + bias
                            original_score = csv_data[index]
                            if csv_header[index] == "貢獻度":
                                adding += original_score
                                continue
                            sum_score += original_score * w
                            sum_w += w
                        weight_score = (sum_score / sum_w) + adding
                        csv_data.append("{:.5f}".format(weight_score))
                        csv_data.append(project["teacher"])
                    writer.writerow(csv_data)
                except Exception as e:
                    print(e)
                    continue
        return send_from_directory(csv_dir, csv_file, as_attachment=True)