예제 #1
0
async def update_players(engine):
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        players = await fpl.get_players(include_summary=True)

    for player in players:
        history = player.history
        history.reverse()

        history_len = min(len(history), 3)
        ict = [0] * 3
        minutes = [0] * 3
        value = [0] * 3

        for i in range(history_len):
            ict[i] += float(history[i]["ict_index"])
            minutes[i] += float(history[i]["minutes"])
            value[i] += float(history[i]["value"])

        ict_form = Models.setHistory(feat_name="player_ict", feat_list=ict)
        minutes_form = Models.setHistory(feat_name="player_minutes",
                                         feat_list=minutes)
        value_form = Models.setHistory(feat_name="player_value",
                                       feat_list=value)

        update_player(player, engine, ict_form, minutes_form, value_form)
예제 #2
0
    def post(self):
        data = request.get_json()
        print(data)
        status, errors = validators.login(data)
        if not status:
            return {"errors": errors}, 401

        user_id = Models.get_user_id_by_email_password(
            data['login'],
            data['password']) or Models.get_user_id_by_username_password(
                data['login'], data['password'])
        print("user id", user_id)
        if not user_id:
            return {'message': 'wrong login details'}, 401

        activated = Models.is_activated(user_id)
        completed = Models.is_completed(user_id)

        print("activated: ", activated)
        if not activated:
            return {'activated': activated, 'message': 'account not activated'}

        print("completed: ", completed)
        token = my_jwt.sign_token(my_jwt.generate_header(),
                                  {'id': str(user_id)})
        notifications.send_login_notification("email")

        print(token)
        return {
            'activated': activated,
            'completed': completed,
            'token': token,
            'message': 'login seccessful'
        }, 201
예제 #3
0
def update_player(Player, session, ict_form, minutes_form, value_form):

    score = None
    if Player.team in team_fixture.keys():
        opposition = team_fixture[Player.team][0]
        if Player.element_type == 1 or Player.element_type == 2:
            tscore = team_score[opposition]
            feat_list = [
                minutes_form,
                float(Player.now_cost), ict_form, value_form, tscore
            ]
            score = Models.setHistory(feat_name="defPlayer_points",
                                      feat_list=feat_list)
        else:
            tscore = team_score[Player.team]
            feat_list = [
                minutes_form,
                float(Player.now_cost), ict_form, value_form, tscore
            ]
            score = Models.setHistory(feat_name="attPlayer_points",
                                      feat_list=feat_list)

    query = text("""UPDATE PLAYER SET element_status = :element_status,
                    chance_of_playing_next_round = :chance_of_playing_next_round,
                    chance_of_playing_this_round = :chance_of_playing_this_round, ep_next = :ep_next,
                    ep_this = :ep_this, event_points = :event_points, form = :form,
                    now_cost = :now_cost, points_per_game = :points_per_game, total_points = :total_points,
                    goals_scored = :goals_scored, assists = :assists, clean_sheets = :clean_sheets,
                    saves = :saves, bonus = :bonus, bps = :bps, influence = :influence, creativity = :creativity,
                    threat = :threat, ict_index = :ict_index, score = :score  WHERE id = :id"""
                 )

    session.execute(
        query,
        element_status=Player.status,
        chance_of_playing_next_round=Player.chance_of_playing_next_round,
        chance_of_playing_this_round=Player.chance_of_playing_this_round,
        ep_next=Player.ep_next,
        ep_this=Player.ep_this,
        event_points=Player.event_points,
        form=Player.form,
        now_cost=Player.now_cost,
        points_per_game=Player.points_per_game,
        total_points=Player.total_points,
        goals_scored=Player.goals_scored,
        assists=Player.assists,
        clean_sheets=Player.clean_sheets,
        saves=Player.saves,
        bonus=Player.bonus,
        bps=Player.bps,
        influence=Player.influence,
        creativity=Player.creativity,
        threat=Player.threat,
        ict_index=Player.ict_index,
        score=score,
        id=Player.id)
예제 #4
0
    def post(self):
        data = request.get_json()
        status, errors = validators.register(data)
        if not status:
            return {"errors": errors}, 404

        activation_code = 'cpf' + str(
            random.randint(100000000000000, 999999999999999)) + 'xvf'
        user_id = Models.add_user(data['username'], data['email'],
                                  data['firstname'], data['lastname'],
                                  data['password'])
        Models.add_activation_code(user_id, activation_code)
        notifications.send_registration_activation_email(
            data['username'], data['email'], user_id, activation_code)
        return {'message': 'registration successful'}, 201
예제 #5
0
def update_team(Team, engine):

    predicted_score = None

    if Team.id in team_fixture.keys():
        opposition = team_fixture[Team.id][0]
        off_strength = team_att_strength[Team.id]
        def_strength = team_def_stength[opposition]
        off_form = team_att_form[Team.id]
        def_form = team_def_form[opposition]
        feat_list = [off_strength, def_strength, off_form, def_form]
        predicted_score = Models.setHistory(feat_name="score",
                                            feat_list=feat_list)

    team_score[Team.id] = predicted_score

    # team_score[Team.id] = predicted_score
    query = text(
        """UPDATE TEAM  SET strength = :strength, strength_overall_home = :strength_overall_home,
                    strength_overall_away = :strength_overall_away, strength_attack_home = :strength_attack_home,
                    strength_attack_away = :strength_attack_away, strength_defence_home = :strength_defence_home,
                    strength_defence_away = :strength_defence_away WHERE id = :id;"""
    )

    engine.execute(query,
                   strength=Team.strength,
                   strength_overall_home=Team.strength_overall_home,
                   strength_overall_away=Team.strength_overall_away,
                   strength_attack_home=Team.strength_attack_home,
                   strength_attack_away=Team.strength_attack_away,
                   strength_defence_home=Team.strength_defence_home,
                   strength_defence_away=Team.strength_defence_away,
                   id=Team.id)
예제 #6
0
async def update_teams(engine):
    async with aiohttp.ClientSession() as session:
        fpl = FPL(session)
        teams = await fpl.get_teams()

        for team in teams:
            if team.id in team_fixture.keys():
                attack_points = [0] * 3
                defence_points = [0] * 3

                squad = await team.get_players()

                for player in squad:
                    player = await fpl.get_player(player.id,
                                                  include_summary=True)
                    history = player.history
                    history.reverse()

                    history_len = min(len(history), 3)

                    for i in range(history_len):
                        if player.element_type == 1 or player.element_type == 2:
                            defence_points[i] = defence_points[i] + history[
                                -1 * i]["total_points"]

                        elif player.element_type == 3 or player.element_type == 4:
                            attack_points[i] = attack_points[i] + history[i][
                                "total_points"]

                team_att = Models.setHistory(feat_name="team_att",
                                             feat_list=attack_points)
                team_def = Models.setHistory(feat_name="team_def",
                                             feat_list=defence_points)

                team_att_form[team.id] = team_att
                team_def_form[team.id] = team_def

                if team_fixture[team.id][1] == "a":
                    team_att_strength[team.id] = team.strength_attack_away
                    team_def_stength[team.id] = team.strength_defence_away
                else:
                    team_att_strength[team.id] = team.strength_attack_home
                    team_def_stength[team.id] = team.strength_defence_home

        for team in teams:
            update_team(team, engine)
예제 #7
0
    def get(self, user_id, activation_key):
        print("___________user_id: " + user_id,
              "_____________code: " + activation_key,
              sep="\n")
        print("expected: ", Models.get_activativation_key(user_id))
        if Models.is_activated(user_id):
            return {'message': 'User account already activated'}, 200

        expected = Models.get_activativation_key(user_id)
        if expected and expected != activation_key:
            print("expected: ", Models.get_activativation_key(user_id))
            print("recieved: ", activation_key)
            return {'message': 'wrong activation key'}, 401

        # activate user:

        Models.remove_activation_code(user_id, activation_key)
        Models.set_profile_activated(user_id)
        return {'message': 'account activated succefully'}, 200
예제 #8
0
 def get(self, interest, id):
     return Models.get_users_with_interest(interest)
예제 #9
0
 def get(self, id):
     print(Models.get_interests_list())
     return Models.get_interests_list()
예제 #10
0
 def get(self, user_id, id=''):
     if user_id != id:
         Models.add_profile_visit(id, user_id)
     return jsonify(Models.get_user_details(user_id))
예제 #11
0
 def get(self, id=''):
     return jsonify(Models.get_users())
    firstname = user['name']['first']
    lastname = user['name']['last']
    username = user['login']['username']
    email = user['email']
    password = user['login']['password']
    gender = user['gender']
    image_url = user['picture']['large']

    address1 = f"{user['location']['street']['number']} {user['location']['street']['name']}"
    address2 = None
    city = user['location']['city']
    state = user['location']['state']
    code = str(user['location']['postcode'])
    longitude = user['location']['coordinates']['longitude']
    latitude = user['location']['coordinates']['latitude']

    print(address1, address2, city, state, code, longitude, latitude, sep='\n')

    user_id = Models.add_user(username, email, firstname, lastname, password)

    Models.set_gender(user_id, gender)
    image_id = Models.add_image(user_id, image_url)
    Models.set_profile_pic(user_id, image_id)
    print(image_id)
    Models.set_sexual_preference(user_id, 'female' if
                                 (gender == 'male') else 'male')
    location_id = Models.add_location(user_id, address1, address2, city, state,
                                      code, longitude, latitude)
    Models.set_location(user_id, location_id)
    print(Models.get_user_details(user_id))
예제 #13
0
def pick_players():
    """
    Get player picks
    """
    if "user_id" in request.cookies and "key" in request.cookies:
        try:
            with db.connect() as engine:

                user_result = engine.execute(
                    sqlalchemy.text(
                        "SELECT * FROM USER_TABLE WHERE id = :id;"),
                    id=int(request.cookies.get("user_id")))

                user = dict(user_result.first())
                fernet = Fernet(request.cookies.get("key"))
                password = fernet.decrypt(
                    user["user_password"].encode()).decode()
                del fernet

                squad, transfer_status = asyncio.run(
                    getUserSquad(user["user_email"], password))

                avltransfers = 2
                if transfer_status["status"] != 'unlimited':
                    avltransfers = transfer_status["limit"] - transfer_status[
                        "made"]

                balance = transfer_status["bank"] * 0.1
                squadIdList = [player["element"] for player in squad]

                query_all = sqlalchemy.text(
                    """WITH all_players as (SELECT p.full_name, t.team_name, t.short_name,
                        p.id, p.code, p.score, p.element_type, p.now_cost, rank() OVER (ORDER BY score desc) as week_rank
                        from PLAYER p, TEAM t where t.id = p.team_id)
                       SELECT * from all_players ORDER BY score DESC;""")

                all_players = [
                    dict(player) for player in engine.execute(query_all)
                ]

                query_squad = sqlalchemy.text(
                    """WITH all_players as (SELECT p.full_name, t.team_name, t.short_name,
                        p.id, p.code, p.score, p.element_type, p.now_cost, rank() OVER (ORDER BY score desc) as week_rank
                        from PLAYER p, TEAM t where t.id = p.team_id)
                       SELECT * from all_players WHERE id = :id ORDER BY score DESC;"""
                )

                user_squad = [
                    dict(player) for id in squadIdList
                    for player in engine.execute(query_squad, id=id)
                ]

                transfers = Models.transfer_algo(all_players, user_squad,
                                                 avltransfers, balance)
                logger.info("GET 200 /pick_transfers")
            return jsonify({"transfers": transfers})
        except:
            logger.error("GET 500 /pick_transfers")
            return make_response(
                {"status": "Invalid: {}".format(sys.exc_info())}, 500)
    logger.error("GET 401 /pick_transfers")
    return make_response({"status": "Not authorized!"}, 401)