3a CPT Video

3ai Program Purpose

  • The purpose of this program is to be able to create a system where user scores are ranked and displayed in a sorted manner based on the user's score.

3aii

  • The video demonstrates the adding of a score to the scoreboard and then ordering the score to its corresponding location after creating the leader, only if the score is greater than 0.

3aiii

  • The inputs and outputs of this program are the following:
    • Inputs:
      • The user's name
      • The user's score
    • Outputs:
      • Success message indicating creation or telling the user score is 0
      • The user's score's location being sorted on the scoreboard
    • These metrics prevent the leaderboard from being cluttered with scores that are 0 and creates the corresponding score table for the games that have been played.

3b

3bi

leader1 = Leader(username='sreeja', score=5)
leader2 = Leader(username='ekam', score=4)
leader3 = Leader(username='tirth', score=3)
leader4 = Leader(username='mani', score=2)
leader5 = Leader(username='user', score=1)
leaders = [leader1, leader2, leader3, leader4, leader5]

3bii

"""Builds sample user/note(s) data"""
    for leader in leaders:
        try:
            leader.create()
        except IntegrityError:
            '''fails with bad or duplicate data'''
            db.session.remove()
            print(f"Records exist, duplicate email, or error: {leader.username}")

3biii

  • The name of the list is called leaders which stores 5 Leader objects. The code snippet above shows the use of a for loop to iterate through the list and follow through the create method in the Leader class which adds the Leader to the Leaderboard SQL table. Which contributes the greater functionality of the program this allows for the creation of a database with data which is then used later in the program through the use of SQL alchemy functions to be able to sort the data in the database and thus generate the filtered leaderboard and be accessed via a get request. Along with the user of other functions such as endpoints to be able to access all the scores of a selected Leader via post request specifying the desired Leader.

3biv

  • The data in the list leaders represent the scores that will be added to the leaderboard and then be sorted by their highest scores.

3bv

  • If the list was not used it would make it so that there would for one not be data to sort and search for user scores as there would be no content in the database thus making it so that the inherent functionality of the program would not be able to be used. Along with the fact that if the list was not used the creation of Leader entries.

3c

3ci

class _Score(Resource):
        def post(self):
            ''' Read data for json body '''
            body = request.get_json()
            username = body.get('username')
            score = body.get('score')
            user = User.query.filter((User._username == username)).first
            # this is checking for garbage data and stopping it 
            if username == 'null':
                return {'message': f'error no login'}, 210
            if user is False:
                return {'message': f'error no user'}, 210
            if int(score) is False or int(score) <= 0:
                return {'message': f'error no score'}, 210
        
            ''' #1: Key code block, setup USER OBJECT '''
            leader = Leader(username=username, score=score)
            # create user in database
            user = leader.create()
            # success returns json of user
            if user:
                return jsonify(user.read())
            # failure returns error
            return {'message': f'Processed {username}, either a format error or score {score} is negative or zero'}, 210

3cii

// Get user ID from local storage
    const userId = localStorage.getItem("userid");

    // Define the endpoint URL
    const url = "http://localhost:8086/api/leadersfiltered/score";

    // Define the request parameters as an object
    const data = {
      username: userId,
      score: matchCounter
    };

    // Define the request options
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    };

    // Send the request with fetch()
    fetch(url, options)
      .then(response => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then(data => {
        console.log(data);
      })
      .catch(error => {
        console.error("There was a problem with the fetch operation:", error);
      });

3ciii

  • The procedure is for creating the Leader object through a post request in which the data that is received is the value from the post request that is for the username and score values. Where goes through selection statements that validate is teh user is a valid user and that if the users score is greater than 0. After which it creates a Leader object and then runs the create method which adds the Leader to the Leaderboard SQL table. Here the values are for the values of UserId and that of the matchCounter representing the user's score these are then used in the call of the function via its api endpoint.

3civ

The procedure begins by taking the values from the body of the post request such as the username and score that is sent then the function checks if the user is a valid user and if the score meets the minimum threshold via the selection statements. After which the function creates a Leader object and then runs the create method which adds the Leader to the Leaderboard SQL table.

3d

3di

Call #1: Call 1

Call #2: Call 2

3dii

What is being tested by the first call is the ability to validate if a user has a score and if not it is not possible for them to be able to send a score through the post endpoint as the users score is not allowed pass due to the selection statement giving an error 210 in the function. What is being tested in the second call is the ability to send a score if the user has a valid score and then showing the score being added to the table and then it is sorted and ranked by the highest score (this portion is a result of a another but related procedure).

3diii

Output #1: Output 1 Output #2: Output 2