コード例 #1
0
ファイル: score.py プロジェクト: Clytra/terraM
    def put(cls, tournament_id, group2):

        tournament = ScoreModel.get_points(tournament_id, group2)

        tournament = ScoreModel.add_pb2(tournament)

        if tournament:
            for row in tournament:
                row.save_to_db()

        return {"scores": [row.json() for row in ScoreModel.find_all(tournament_id)]}
コード例 #2
0
ファイル: score.py プロジェクト: Clytra/terraM
    def put(cls, tournament_id):

        sumPoints = ScoreModel.get_all_members(tournament_id)

        sumPoints = ScoreModel.pb_summary(sumPoints)

        if sumPoints:
            for row in sumPoints:
                row.save_to_db()

        return {"scores": [row.json() for row in ScoreModel.get_finalists(tournament_id)]}
コード例 #3
0
    def post(self, quiz_id):
        data = parser.parse_args()
        data['quiz_id'] = quiz_id

        score = ScoreModel(**data)
        try:
            score.save()
        except:
            return {"message": "An error occurred while inserting Score."}, 500

        return score.json(), 201
コード例 #4
0
ファイル: score.py プロジェクト: Clytra/terraM
    def put(cls, tournament_id, user_id):

        tournament = ScoreModel.get_all_members(tournament_id)
        user = ScoreModel.get_user(user_id)

        tournament = ScoreModel.add_second_tie_breaker(tournament, user, user_id)

        if tournament:
            for row in tournament:
                row.save_to_db()

        return {"scores": [row.json() for row in ScoreModel.find_all(tournament_id)]}
コード例 #5
0
ファイル: score.py プロジェクト: Clytra/terraM
    def put(cls, tournament_id):

        tournament = ScoreModel.get_all_members(tournament_id)
        number = len(tournament)

        tournament = ScoreModel.get_number_of_tables(number, tournament)

        if tournament:
            for row in tournament:
                row.save_to_db()

        return {"scores": [row.json() for row in ScoreModel.find_all(tournament_id)]}
コード例 #6
0
    def post(self):

        data = Score.parser.parse_args()

        score = ScoreModel(**data)

        try:
            score.save_to_db()
        except:
            return {"message": "An error occurred inserting the score."}, 500

        return score.json(), 201
コード例 #7
0
ファイル: score.py プロジェクト: Clytra/terraM
    def delete(cls, tournament_id, user_id):
        claims = get_jwt_claims()
        if not claims['is_admin']:
            return {'message': ADMIN_PERMISSION}, 401
        tournament = ScoreModel.find_by_id(tournament_id)
        member = ScoreModel.find_by_id(user_id)

        if tournament:
            if member:
                member.delete_from_db()
                return {"message": SUCCESS_DELETING}, 200
            return {"message": ITEM_NOT_FOUND}, 404
        return {"message": ITEM_NOT_FOUND}, 404
コード例 #8
0
ファイル: usertournament.py プロジェクト: Clytra/terraM
    def put(cls, user_id, tournament_id):

        tournament = TournamentModel.find_by_id(tournament_id)
        user = UserModel.find_by_id(user_id)

        if user is not None:
            tournament.members.append(user)
            db.session.commit()
            db.session.close()

        score = ScoreModel(has_own_game=0,
                           status='uczestnik',
                           end_terra_first=0,
                           end_terra_second=0,
                           group1=None,
                           group2=None,
                           pz1=None,
                           pz2=None,
                           pz3=None,
                           pb1=None,
                           pb2=None,
                           pb_sum=None,
                           tb1=None,
                           tb2=None,
                           user_id=user_id,
                           tournament_id=tournament_id)
        user.scores.append(score)
        db.session.add(user)
        db.session.commit()
        db.session.close()
コード例 #9
0
 def get(cls, user_id):
     return {
         'message':
         'success',
         'content':
         [score.json() for score in ScoreModel.find_by_user_id(user_id)]
     }
コード例 #10
0
    def get(self, quiz_id, score_id):
        score = ScoreModel.find_by_id(score_id)

        if score is None:
            return {"message": "No score found."}, 404

        return score.json(), 200
コード例 #11
0
ファイル: score.py プロジェクト: Clytra/terraM
    def delete(cls, user_id: int, tournament_id: int):

        score = ScoreModel.find_by_id(user_id, tournament_id)

        if not score:
            return {"message": ITEM_NOT_FOUND}, 404
        score.delete_from_db()
        return {"message": SUCCESS_DELETING}, 200
コード例 #12
0
    def delete(cls, user_id):
        for score in ScoreModel.find_by_user_id(user_id):
            score.remove_from_db()

        return {
            'message':
            f'Successfully deleted all scores for user \"{user_id}\".'
        }
コード例 #13
0
    def get(cls, user_id):
        score = ScoreModel.get_latest(user_id)

        if score:
            return {
                "message": "Successfully retrieved the latest score",
                'content': score.json()
            }
        return {"message": "No scores available for this user."}, 404
コード例 #14
0
def client():
    """ Testing client for the scores service """
    app.config.from_object('config.TestingConfig')
    app.app_context().push()
    db.init_app(app)

    client = app.test_client()
    db.create_all()

    ScoreModel('foo', 'test1', {'notes': []}, True).save_to_db()
    ScoreModel('bar', 'test1', {'notes': []}, False).save_to_db()
    ScoreModel('foo', 'test2', {'notes': []}, False).save_to_db()
    ScoreModel('bar', 'test2', {'notes': []}, True).save_to_db()

    yield client

    db.session.close()
    db.drop_all()
コード例 #15
0
    def delete(cls, user_id, score_name):
        score = ScoreModel.find_by_name(user_id, score_name)

        if score:
            score.remove_from_db()

            return {
                'message':
                f'Successfully removed score \"{score_name}\" from the database.'
            }
        return cls.fail_response(score_name)
コード例 #16
0
    def post(cls):
        '''Upload user submission'''
        try:
            user_mail = get_jwt_identity()

            # check current submission counts
            daily_counts = FileModel.get_interval_upload_count_by_mail(
                email=user_mail, AOEtime=get_AOE_today(to_str=False))
            weekly_counts = FileModel.get_interval_upload_count_by_mail(
                email=user_mail, AOEtime=get_AOE_week(to_str=False))
            if (daily_counts >= configs["DAILY_SUBMIT_LIMIT"]) or (weekly_counts >= configs["WEEKLY_SUBMIT_LIMIT"]):
                return {"message": f"Exceed Submission Limit: You have submitted {daily_counts} times today and {weekly_counts} times this week."}, HTTPStatus.FORBIDDEN

            # file validation
            file = request.files['file']

            if file.filename == "":
                return {"message": "No file selected."}, HTTPStatus.FORBIDDEN
            if not file_upload.zipfile_check(file):
                return {"message": "Wrong file format."}, HTTPStatus.FORBIDDEN

            # load form data
            formData = publicFormSchema.load(request.form)

            # get file path
            upload_count = FileModel.get_upload_count_by_mail(
                email=user_mail) + 1
            folder = file_upload.create_folder(user_mail, str(upload_count))
            file_path = file_upload.get_full_path(folder, file.filename)

            # add column for db
            formData.update({"email": user_mail, "filePath": file_path})

            fileObj = FileModel(**formData)
            scoreObj = ScoreModel()
            fileObj.scores.append(scoreObj)
            fileObj.save_to_db()
            try:
                file.save(file_path)

                # start processing
                thread = Thread(target=metric_calculate_pipeline, kwargs={"file_path": file_path,
                                                                          "submitUUID": formData["submitUUID"]})
                thread.start()

                return {"message": "Upload successfully!"}, HTTPStatus.OK
            except Exception as e:
                fileObj.delete_from_db()  # Rollback
                return {"message": "Internal Server Error!"}, HTTPStatus.INTERNAL_SERVER_ERROR
        except ValidationError as e:
            return {"message": "There's something worng with your input!"}, HTTPStatus.BAD_REQUEST
        except Exception as e:
            print(e)
            return {"message": "Internal Server Error!"}, HTTPStatus.INTERNAL_SERVER_ERROR
コード例 #17
0
    def delete(self, quiz_id, score_id):
        score = ScoreModel.find_by_id(score_id)

        if score is None:
            return {"message": "No score found."}, 404

        try:
            score.delete()
        except:
            return {"message": "An error occurred while deleting Score."}, 500

        return {"message": "Score deleted."}, 200
コード例 #18
0
ファイル: score.py プロジェクト: Clytra/terraM
    def put(cls, tournament_id):

        check_owners = ScoreModel.get_all_members(tournament_id)
        groups2 = []

        if check_owners:
            for row in check_owners:
                if row.has_own_game:
                    row.group2 = row.group1
                    groups2.append(row.group2)
                    row.save_to_db()

        tournament = ScoreModel.get_group2(tournament_id)

        number = len(tournament)

        tournament = ScoreModel.get_number_of_tables2(number, tournament, groups2)

        if tournament:
            for row in tournament:
                row.save_to_db()

        return {"scores": [row.json() for row in ScoreModel.find_all(tournament_id)]}
コード例 #19
0
    def patch(cls, user_id, score_name):
        data = cls.parser.parse_args()

        names = (score.name for score in ScoreModel.find_by_user_id(user_id))

        if data['name'] in names:
            return {
                'message': 'This name is already used. Try a different one.'
            }, 409

        score = ScoreModel.find_by_name(user_id, score_name)

        if score:
            for key, val in data.items():
                if val is not None:
                    setattr(score, key, val)

            score.last_edit = datetime.datetime.now()
            score.save_to_db()
            return {
                'message': f'Successfully updated score \"{score_name}\".',
                'content': score.json(),
            }
        return cls.fail_response(score_name)
コード例 #20
0
ファイル: score.py プロジェクト: Clytra/terraM
    def put(cls, user_id: int, tournament_id: int):

        data = Score.parser.parse_args()
        score = ScoreModel.find_by_id(user_id, tournament_id)
        if score:
            score.has_own_game = data['has_own_game']
            score.end_terra_first = data['end_terra_first']
            score.end_terra_second = data['end_terra_second']
            score.status = data['status']
            score.group1 = data['group1']
            score.group2 = data['group2']
            score.pz1 = data['pz1']
            score.pz2 = data['pz2']
            score.pz3 = data['pz3']
        try:
            score.save_to_db()
        except:
            return {"message": ERROR_EDITING}, 500

        return score.json(), 200
コード例 #21
0
ファイル: score.py プロジェクト: willzzini/challenge-rest-api
    def post(self, type_risk):
        if ScoreModel.find_by_name(type_risk):
            return {
                'message':
                "A score with type_risk '{}' \
                    already exists.".format(type_risk)
            }, 400

        score = ScoreModel(type_risk)
        try:
            score.save_to_db()
        except:
            return {"message": "An error occurred creating the score."}, 500

        return score.json(), 201
コード例 #22
0
ファイル: score.py プロジェクト: Clytra/terraM
    def get(cls, tournament_id):
        scores = [score.json() for score in ScoreModel.find_all(tournament_id)]
        if scores:
            return {"scores": scores}, 200
        return {"message": ITEM_NOT_FOUND}, 404


#    def get(self):
#        scores = [score.json() for score in ScoreModel.find_all()]
#        return {'scores': scores}, 200
#    @jwt_optional
#    def get(self):
#        user_id = get_jwt_identity()
#        scores = [score.json() for score in ScoreModel.find_all()]
#        if user_id:
#            return {'scores': scores}, 200
#        return (
#            {
#                'scores': [score[''] for score in scores],
#                'message': 'Więcej informacji po zalogowaniu.'
#            }
#        )
コード例 #23
0
    def put(self, quiz_id, score_id):
        data = parser.parse_args()

        score = ScoreModel.find_by_id(score_id)

        if score is None:
            new_score = ScoreModel(**data)
            try:
                new_score.save()

                return new_score.json(), 201
            except:
                return {"message": "An error occurred while inserting Score."}, 500
        try:
            score.update(**data)
        except:
            return {"message": "An error occurred while updating Score."}, 500

        return score.json(), 200
コード例 #24
0
    def post(cls, user_id):
        data = cls.parser.parse_args()

        names = (score.name for score in ScoreModel.find_by_user_id(user_id))

        if data['name'] not in names:
            new_score = ScoreModel(data['name'],
                                   user_id,
                                   data['score'],
                                   public=data['public'],
                                   description=data['description'])
            new_score.save_to_db()

            return {
                'message': 'Successfully added new score.',
                'content': new_score.json()
            }
        return {
            'message':
            f'Name \"{data["name"]}\" was already used, try different name.',
        }, 409
コード例 #25
0
    def get(cls, user_id, score_name):
        score = ScoreModel.find_by_name(user_id, score_name)

        if score:
            return {'message': 'success', 'content': score.json()}
        return cls.fail_response(score_name)
コード例 #26
0
    def get(self, quiz_id):
        scores = ScoreModel.find_by_quiz(quiz_id)

        return [score.json() for score in scores], 200
コード例 #27
0
ファイル: score.py プロジェクト: willzzini/challenge-rest-api
 def get(self, type_risk):
     score = ScoreModel.find_by_name(type_risk)
     if score:
         return score.json()
     return {'message': 'Score not found'}, 404
コード例 #28
0
ファイル: score.py プロジェクト: willzzini/challenge-rest-api
    def delete(self, type_risk):
        score = ScoreModel.find_by_name(type_risk)
        if score:
            score.delete_from_db()

        return {'message': 'Score deleted'}
コード例 #29
0
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))
コード例 #30
0
 def delete(self, tag):
     score = ScoreModel.find_by_tag(tag)
     if score:
         score.delete_from_db()
         return {'message': 'score deleted.'}
     return {'message': 'score not found.'}, 404