Review Topics

All of the topics below are things that have been heavily covered and used throughout the class. We will mostly be focusing on more complicated uses and mechanics of these topics.

Lists

  • What are Lists?

    • Lists are an ordered sequence of elements, where each element is a variable
    • Unlike dictionaries, lists' keys are all integers that describe the order of the list
  • Some examples of lists:

    • Playlist of songs
    • names of students in a class
    • contacts on your phone
  • Each element of a string is referenced by an index (which is a number) and they generally start 0 but for the AP Exam it starts at 1.

    • AP Exam: 1,2,3,4 etc.
    • Python: 0,1,2,3 etc.

How do lists Manage Complexity of a program?

  • We may not need as many variables. For example:
    • One Variable that holds all students would be better than having a variable for EACH student
    • There can also be a list of test scores so if they need to be curved then the same calculation can be applied to the list (that has all the students) instead of doing the calculations one at a time

Answer the following questions about the code block below:

  • Why do you think lists are helpful? What word does College Board like to use to describe the function of lists?
    • Lists store data in them and are useful for storage. Collegeboard likes to use the word "abstraction" to describe the function of lists, as complex data structures are simplified.
# variable of type string
name = "Sri Kotturi"
print("name", name, type(name))

# variable of type integer
age = 16
print("age", age, type(age))

# variable of type float
score = 90.0
print("score", score, type(score))

print()

# variable of type list (many values in one variable)
langs = ["Python", "JavaScript", "Java", "Bash", "html"]
print("langs", langs, type(langs))
print("- langs[2]", langs[2], type(langs[2]))

print()

# variable of type dictionary (a group of keys and values)
person = {
    "name": name,
    "age": age,
    "score": score,
    "langs": langs
}
print("person", person, type(person))
print('- person["name"]', person["name"], type(person["name"]))
name Sri Kotturi <class 'str'>
age 16 <class 'int'>
score 90.0 <class 'float'>

langs ['Python', 'JavaScript', 'Java', 'Bash', 'html'] <class 'list'>
- langs[2] Java <class 'str'>

person {'name': 'Sri Kotturi', 'age': 16, 'score': 90.0, 'langs': ['Python', 'JavaScript', 'Java', 'Bash', 'html']} <class 'dict'>
- person["name"] Sri Kotturi <class 'str'>

Mathematical Expressions

What is the output of the cell below? What Mathematical Expressions do you see being used? (List them below.)

  • The output of the cell below is 10.
  • The mathematical expression I see being used is + which adds two inputs. I also see // which means floor division. If the output of (grade 1 + grade)/2 is a decimal, then it rounds down.
grade1 = 10
grade2 =  grade1 

average_grade = (grade1 + grade2) // 2 #what are these two slashes?

print(average_grade)
10

What is the value of num1, num2, and num3? Explain how each number ended up what it was.

  • The original value of num1 was 2. The value was then changed to num2^num3 which is 4^6. This is 4096 and thats why 4096 was outputted when you run the program.
  • The original value of num2 was 4. The value was then changed to (num1 + num3)//9. The // symbol means floor division which means it adds num1 and num3 and then divides the sum by 9. If the answer includes a decimal, then it would round down. num1 + num3 is 4097 and when you divide that by 9 and round down, you get 455 and thats why 455 was outputted when you run the program.
  • The original value of num3 was 6. The value was then changed to num1%5 which is 4096%5. The % symbol represents the mod function which divides num 1 by 5 and then outputs the remainder. In this case, 4096%5 is 1 and thats why 1 was outputted when you run the program.
num1 = 2
num2 = 4
num3 = 6
num1 = num2 ** num3
num3 = num1 % 5
num2 = (num1 + num3) // 9

print(num1)
print(num2)
print(num3)
4096
455
1

Selection

Selection refers to the process of making decisions in a program based on certain conditions. It is normally done with conditional statements.

Conditionals

What is a conditional?:

  • Statement that allows code to execute different instructions if a certain condition is true or false
  • Allows program to make decisions based on data and input

What are the main types of conditional statements?:

  • if
  • elif
  • else

If statements

  • The if statement is used to check if a certain condition is true. The condition can be any expression that evaulates to a boolean value, True or False. If the condition is True, then it executes a code block.
  • If (condition) then (consequence)
  • Example:
x = int(input("Enter a number"))
if x > 0: # if condition, check if this is true of false
    print("x is positive") # code that will execute if condition is met
x is positive

Else

  • The else statemnt executes a code block when the if condition is False.
  • If (condition) then (consequence A), else (consequence B)

Elif

  • The elif statement can check multiple conditions in a sequence, and execute a certain block of code if any of the conditions are true.
  • If (condition) then (consequence A), elif (condition) then (consequence B), else (consequence C)

  • Example adding onto the code from before to take negative numbers and 0 into account

x = int(input("Enter a number, x:"))
if x > 0: # if condition, check if this is true of false
    print("x is positive") # code that will execute if condition is met
elif x < 0: # if previous condition not true... elif condition, check if this is true of false
    print("x is negative")# code that will execute if condition is met
else: # everything else, in this case it is if x == 0 
    print("x is zero") # only executes if all previous conditions are not met
x is positive

Nested Conditionals

What is a nested conditional?:

  • Conditional statement inside another conditional statement
  • Allows to check for more complex condition where one condition depends on another

Nested Conditional Statements

  • Example
x = int(input("Enter a number, x:"))
if x % 2 == 0:
    print("x is even divisible by 2")
    # only ever checks is x is divisble by 3 if x is even. nested conditional
    if x % 3 == 0:
        print("x is divisible by 3")
    else:
        print("x is not divisible by 3")
else:
    print("x is odd")
x is even divisible by 2
x is divisible by 3

Indentation

When using conditionals and nested conditionals in Python, it is important to pay attention to the level of indentation in the code. The code inside the if, elif, and else blocks must be indented so they are nested within the outer statements. This way, Python knows which code belongs to which block.

What is binary search and what is it used for?:

  • Searching algorithm
  • Find and select a specific element in a sorted list of elements

How does binary search work?:

  • Repeatedly divides the search interval in half to find the middle element and compares the middle value to the target value, if not the same then it continues on to either the lower or upper half
  • Eliminate half of the remaining search interval elements each time
  • Efficient way to search for element in large dataset

What is the time complexity and why?:

  • O(log(N))
  • The maximum number of iterations is the amount of times the list can be divided in half until it reaches 1 number
  • Dividing by 2, so it is log2(N), logarigthm of n base 2

  • You may recognize the example below from the binary lesson last Friday

import random

def binary_search_game():
    low = 1
    high = 100
    target = random.randint(low, high)

    while True:
        guess = (low + high) // 2
        print(f"Is your number {guess}?")
        response = input("Enter 'higher', 'lower', or 'yes': ")

        # conditional statements to check target number and guess
        if response == 'yes':
            print(f"I guessed your number {guess}!")
            break
        elif response == 'higher':
            low = guess + 1
        elif response == 'lower':
            high = guess - 1
        else:
            print("Invalid input, please enter 'higher', 'lower', or 'yes'.")

binary_search_game()
Is your number 50?
Is your number 25?
Is your number 12?
I guessed your number 12!

Quick Hack

Write a program using conditionals and nested conditionals

  • Ideas: Quiz, game (rock paper scissors, guess number), etc
import random

user_action = input("Enter a choice (rock, paper, scissors): ")
possible_actions = ["rock", "paper", "scissors"]
computer_action = random.choice(possible_actions)
print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")

if user_action == computer_action:
    print(f"You both chose {user_action}. Try again!")
elif user_action == "rock":
    if computer_action == "scissors":
        print("Rock beats scissors! You win!")
    else:
        print("Paper beats rock! You lose.")
elif user_action == "paper":
    if computer_action == "rock":
        print("Paper beats rock! You win!")
    else:
        print("Scissors beats paper! You lose.")
elif user_action == "scissors":
    if computer_action == "paper":
        print("Scissors beats paper! You win!")
    else:
        print("Rock beats scissors! You lose.")
You chose rock, computer chose scissors.

Rock beats scissors! You win!

Introduction to Algorithms

  • an algorithm is a et of instructions that describes how to solve a problem or perform a specific task using a computer program.
  • It is a precise sequence of computational steps that take an input and produce an output

How do Algorithms relate to data structures?

  • Algorithms often rely on specific data structures to solve problems efficiently.
  • Sorting algorithms require a data structure such as an array or a linked list to store and manipulate data.
  • Searching algorithms such as binary search require data structures like arrays or trees to organize and search through data.

Important Terms

What is an algorithm?

  • it is a finite set of instructions that accomplishes a specific task

Sequencing

  • means that there is an order in which to do things

Selection

  • Helps to choose two different outcomes based off of a decision that the programmer wants to make

Iteration

  • Repeat something until the condition is met. (also referred to as repetition)

Calling and Developing Procedures

  • A procedure is a sequence of instructions that performs a specific task.
  • To call a procedure, you need to know its name and any arguments it requires.
  • When a procedure is called, the program jumps to its instruction and starts executing it.
  • The arguments passed to a procedure can be used within the procedure to perform tasks or calculations.
  • After the procedure has completed its task, it returns control back to the calling program.
def add_numbers(a, b):
    sum = a + b
    print("The sum of", a, "and", b, "is", sum)

# Call the procedure with arguments 5 and 7
add_numbers(5, 7)
The sum of 5 and 7 is 12
  • The result of the procedure can be stored in a variable, printed to the screen, or used in any other way that is required by the program.
  • Procedures can be defined within the same program or in external files, and can be reused across multiple parts of the program.
  • To avoid errors and improve code readability, it's important to define and call procedures with proper syntax and conventions that are appropriate for the programming language you're using.
def calculate_average(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return average

# Call the procedure with a list of numbers
numbers_list = [10, 20, 30, 40, 50]
result = calculate_average(numbers_list)

# Display the result
print("The average of", numbers_list, "is", result)
The average of [10, 20, 30, 40, 50] is 30.0

Algorithmic Efficiency

  • Algorithmic efficiency refers to the amount of time and resources needed to execute an algorithm.
  • The efficiency of an algorithm can be measured in terms of its time complexity and space complexity.
    • Time complexity refers to the amount of time required by an algorithm to complete its task as a function of its input size.
    • Space complexity refers to the amount of memory required by an algorithm to complete its task as a function of its input size.
    • can be analyzed using Big O notation, which provides an upper bound on the worst-case time and space complexity of the algorithm.

What is the time complexity of the following code:

  • O(N)
  • O(N*log(N))
  • O(N * Sqrt(N))
  • O(N*N)
a = 0
for i in range(N):
  for j in reversed(range(i, N)):
    a = a + i + j

The time complexity will be O(N*N) because there is a nested for loop - or two for loops consecutively - which causes the time complexity of N to be squared.

What will be the time complexity of the following code?

  • n
  • (n+1)
  • n(n-1)
  • n(n+1)
value = 0
for i in range(n): #iterates "n" times, with "i" taking on values from 0 to n-1.
  for j in range(i): # iterates "i" times, with "j" taking on values from 0 to i-1.
    value=value+1

n(n+1) n(n+1) because there are two for loops, and therefore n is iterated through twice. There is also the +1 becaue each time, a value is added by 1.

  • Efficiency can be improved by optimizing algorithms or by using more efficient data structures and algorithms.
    • Some common techniques for improving efficiency include reducing the size of the input data, caching results, and parallelizing tasks.
    • Understanding algorithmic efficiency is important in software development, as it can impact the performance of applications and their ability to scale with larger data sets.

Iteration and Simulations

Simulations are models of real-world phenomena or systems that use mathematical algorithms and computer programs simulate the real behavior and aspects of the subject being modeled.

Simulations are most often used to model complex or time-consuming things that would be difficult to test in real life, such as modeling the spread of diseases in certain ecosystems or testing the functionality of a potential product before it is made.

In this lesson, we will be looking at lists, iteration, and random values through the lens of simulations.

PLEASE RUN THE CODE BELOW BEFORE INTERACTING WITH THE CODE SEGMENTS IN THIS SECTION!

class Card:
    def __init__(self, suit, val):
        self.suit = suit
        self.val = val
        if val == 11:
            self.kind = "Ace"
        elif val == 12:
            self.kind = "Jack"
        elif val == 13:
            self.kind = "Queen"
        elif val == 14:
            self.kind = "King"
        else:
            self.kind = str(self.val)

    #return a formatted string version of a card
    def show(self):
        return f"{self.kind} of {self.suit}"
    
    #adjust aces to prevent breaking
    def ace_adj(self):
        if self.kind == "Ace":
            self.val = 1

Review: Lists and Iteration

Lists and iteration work hand-in-hand to efficiently process and/or modify multiple values at once. In a card game, for example, lists and iteration are used together frequently to make the game work correctly.

For Loops

For loops are probably the most well-known type of iterative loop used in code. Most of us know about the for variable in list format.

One helpful tool not a lot of people know about is the enumerate() function. When used in conjunction with a for loop, you can always have access to the index and value of each selected list entry.

numlist = [3, 5, 68, 203]

for key, num in enumerate(numlist):
    print(f"This entry's index is {str(key)}, but its value is {str(num)}.")
    print(f"The difference between the value and the index is {num - key}.")
This entry's index is 0, but its value is 3.
The difference between the value and the index is 3.
This entry's index is 1, but its value is 5.
The difference between the value and the index is 4.
This entry's index is 2, but its value is 68.
The difference between the value and the index is 66.
This entry's index is 3, but its value is 203.
The difference between the value and the index is 200.

QUESTION: How is the key, num in enumerate(list) format similar to the format used when applying a for loop to a dictionary?

Answer: When running a for loop to a dictionary, the loop iterates through the keys and values. Similarly, this format iterates through the index and the values, which is like the keys and values of dictionaries.

List Comprehension

You may also see for loops used within a list like below. We went over this in class fairly recently. In this case, it is used to show the cards in the hand of a player.

player_hand = [] # the player's hand is represented as a list
# because lists are mutable (can change), they can be added to, like drawing a card

# assume the deck below is a a deck of shuffled cards
deck = [Card("Hearts", 3), Card("Spades", 12), Card("Diamonds", 11)]
def draw_card(hand, deck):
    hand.append(deck.pop())

#try it out
draw_card(player_hand, deck)
print([card.show() for card in player_hand])
['Ace of Diamonds']

Recursive Loops

Recursive loops have you calling one function inside of another. If a function must make some change to a certain value multiple times, it is oftem most efficient to have a function call itself with slightly different arguments like the fibonacci sequence below.

def fibonacci(terms):
    if terms <= 1:
        return terms
    return fibonacci(terms-1) + fibonacci(terms-2)

fibonacci(5)
5

Nesting Loops

Nesting loops increases the time complexity of the program, but it can be used to do things like make a card deck (see below).

def build(deck):
        for suit in ["Spades", "Clubs", "Diamonds", "Hearts"]:
            for val in range(2, 15): #HINT: try replacing this function
                deck.append(Card(suit, val))

While Loops

While loops aren't used in the program, but they offer a different way to repeat a set of instructions in a program. The procedure below the while [condition] line will occur until the condition is made not true.

Student Interaction: How could this build function be altered to function with a while loop within it?

def build(deck):
        for suit in ["Spades", "Clubs", "Diamonds", "Hearts"]:
            for val in range(2, 15):
                deck.append(Card(suit, val))

#HINT: you may want to make an incrementing i variable

While loops also alter an alternative way to loop a set of instructions forever, until a precise thing occurs to break the loop. See the code below.

import random
i = 0

while True:
    i += 1
    ch = random.randint(1, 11)
    if ch == 10:
        print(f"It took {str(i)} random generations to get 10.")
        break
It took 12 random generations to get 10.

49 random generations is a lot more than it would normally take, but it's important for code to be able to model unlikely, yet possible scenarios. Speaking of random values...

Random Values

Because unpredictable randomness occurs in the real world, it's important to have a way to represent it. Simulations are able to use randomization, which could be in the form of random number generation or other methods like shuffle.

Card decks are a great example of how random values can be used to represent real-world scenarios. In the card simulation, the random module's shuffle function is used to quite literally shuffle the deck, seen below.

def shuffle(deck):
    random.shuffle(deck)

Often, random selection methods use functions like randint or randrange as ways to select certain indexes in lists, or might use the random numbers in some other way.

QUESTION: Without shuffling the card order of the deck, can you think of a way that the aforementioned random module functions could be used to get a random card from the deck? Do so in the code cell below.

  • The randint function can be used to randomly generate an index from the deck.
import random

#find another random function that could pull a random card from a deck of UNSORTED cards

Simulation Homework

Now that you've learned about simulations and how they're used, it's time to apply that knowledge by creating a (basic) simulation of a real-world scenario. It can be something in nature, like the changes in the wildlife population of a certain area; it can be a game, like Uno (no blackjack though, that's taken); or it can be something completely random and unique.

The simulation must include...

  • Use of at least one random value
    • The simulation uses a random value to simulate the dice roll.
  • At least one list or similar data type (dictionary, set, etc.)
    • The simulation uses a list to represent the game board.
  • Efficient use of iteration (must support the purpose of the simualtion)
    • The simulation uses iteration to determine the player's position on the board.
  • Selection (use of conditionals)
    • The simulation uses conditionals to determine the player's position on the board.

Do this in your student copy in the cell provided. This is worth 0.9 (or more with extra credit) out of the 3 possible points.

# (Concert attendance? Wind speeds? Interactions between subjects in large environments?)

# Think about the sort of things that could be saved in lists, dictionaries, etc.
# (Even better if you can take advantage of the specific features of multiple types of data sets!)

# What kind of iteration happens in the real world?
# What occurs repeatedly, even over a long period of time?
# You could model the results of a disease spreading through a population without it taking IRL years.

import random

# Set up the game board
board = ["Start", "Square 1", "Square 2", "Square 3", "Square 4", "Square 5", "Finish"]
num_squares = len(board)
player_pos = 0

# Roll the dice and move the player
while player_pos < num_squares - 1:
    roll = random.randint(1, 6)
    print("You rolled a", roll)
    player_pos += roll
    if player_pos >= num_squares:
        player_pos = num_squares - 1
    print("You are now on", board[player_pos])
    
print("Congratulations, you reached the finish!")
You rolled a 4
You are now on Square 4
You rolled a 3
You are now on Finish
Congratulations, you reached the finish!

Databases

We have already gone over databases in this class, but here is a refresher. A database contains data that's stored in columns and rows. The information in this database can then be pulled from the database and can be used in a program.

Setting Up the Database

Run the code cell below to prepare SQLite to create the database. If your system is struggling with the flask functions, verify that you're in the correct Python environment. REMEMBER: You should only db.init_app(app) ONCE during the process!

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# Setup of key Flask object (app)
app = Flask(__name__)
# Setup SQLAlchemy object and properties for the database (db)
database = 'sqlite:///sqlite.db'  # path and filename of database
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = database
app.config['SECRET_KEY'] = 'SECRET_KEY'
db = SQLAlchemy()


# This belongs in place where it runs once per project
db.init_app(app)

The Model File

The model file plays a crucial role in the formation of the database.

  • The model helps to create new databases
  • It provides a standardized method for formating the database entries across different systems
  • Objects used within the database are created
import os, base64
import json
from sqlalchemy.exc import IntegrityError

# Define the User class to manage actions in the 'users' table
class User(db.Model):
    __tablename__ = 'players'  # table name is plural, class name is singular

    # Define the User schema with "vars" from object
    id = db.Column(db.Integer, primary_key=True)
    _username = db.Column(db.String(255), unique=False, nullable=False)
    _streak = db.Column(db.Integer, unique=True, nullable=False)

    # constructor of a User object, initializes the instance variables within object (self)
    def __init__(self, username, streak):
        self._username = username
        self._streak = streak

    # a username getter method, extracts username from object
    @property
    def username(self):
        return self._username
    
    # a setter function, allows username to be updated after initial object creation
    @username.setter
    def username(self, username):
        self._username = username
    
    # a getter method, extracts streak from object
    @property
    def streak(self):
        return self._streak
    
    # a setter function, allows streak to be updated after initial object creation
    @streak.setter
    def streak(self, streak):
        self._streak = streak
    
    # output content using str(object) in human readable form, uses getter
    # output content using json dumps, this is ready for API response
    def __str__(self):
        return json.dumps(self.read())

    # CRUD create/add a new record to the table
    # returns self or None on error
    def create(self):
        try:
            # creates a person object from User(db.Model) class, passes initializers
            db.session.add(self)  # add prepares to persist person object to Users table
            db.session.commit()  # SqlAlchemy "unit of work pattern" requires a manual commit
            return self
        except IntegrityError:
            db.session.remove()
            return None

    # CRUD read converts self to dictionary
    # returns dictionary
    def read(self):
        return {
            "id": self.id,
            "username": self.username,
            "streak": self.streak
        }

    # CRUD update: updates user name, password, phone
    # returns self
    def update(self, username, streak):
        """only updates values with length"""
        if len(username) > 0:
            self.username = username
        if streak > 0:
            self.streak = streak
        db.session.commit()
        return self

    # CRUD delete: remove self
    # None
    def delete(self):
        db.session.delete(self)
        db.session.commit()
        return None


"""Database Creation and Testing """

# Builds working data for testing
def initUsers():
    with app.app_context():
        """Create database and tables"""
        db.create_all()
        """Tester data for table"""
        u1 = User(username="Mr. Cards", streak=5)
        u2 = User(username="Kard Kowntre", streak=10)
        u3 = User(username="Un Bea Table", streak=15)

        users = [u1, u2, u3]

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

The init Fuction

The init method has one purpose which is to initialize the object's attributes. This is what is known as the constructor. In our project, the init method initalizes the username and streak as variables.

    def __init__(self, username, streak):
        self._username = username
        self._score = streak

Setters and Getters

Setters and Getters are important methods used when writing code for databases.

  • Setter: a method that allows us to set or change the value of an attribute in a class.
  • Getter: a method that allows us to access an attribute in a given class.

Setter Example

@streak.setter
def streak(self, streak):
self._streak = streak

Getter Example

@property
def streak(self):
return self._streak

The Api File

An API is an important part of having a functional database.

  • it acts as a messenger that allows programs to access data from the others
  • it connects all information
  • for a database, an api retrieves the data requested in code for the user
import json
from flask import Blueprint, request, jsonify
from flask_restful import Api, Resource # used for REST API building

user_api = Blueprint('user_api', __name__,
                   url_prefix='/api/users')

api = Api(user_api)

class UserAPI:        
    class _CRUD(Resource):  # User API operation for Create, Read.  THe Update, Delete methods need to be implemeented
        def post(self): # Create method
            ''' Read data for json body '''
            body = request.get_json()
            
            ''' Avoid garbage in, error checking '''
            # validate name
            username = body.get('username')
            if username is None or len(username) < 1:
                return {'message': f'Username is missing, or is less than a character'}, 400
            # validate uid
            streak = body.get('streak')
            if streak is None or streak < 1:
                return {'message': f'Streak is missing, or is less than 1'}, 400

            ''' #1: Key code block, setup USER OBJECT '''
            uo = User(username=username, 
                      streak=streak)
            
            ''' #2: Key Code block to add user to database '''
            # create user in database
            user = uo.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 a duplicate'}, 400

        def get(self): # Read Method
            users = User.query.all()    # read/extract all users from database
            json_ready = [user.read() for user in users]  # prepare output in json
            return jsonify(json_ready)  # jsonify creates Flask response object, more specific to APIs than json.dumps

        def put(self):
            body = request.get_json() # get the body of the request
            id = body.get('id')
            username = body.get('username')
            streak = body.get('streak') # get the UID (Know what to reference)
            user = User.query.get(id) # get the player (using the uid in this case)
            user.update(username=username, streak=streak)
            return f"{user.read()} Updated"

        def delete(self):
            body = request.get_json()
            id = body.get('id')
            player = User.query.get(id)
            player.delete()
            return f"{player.read()} Has been deleted"

    # building RESTapi endpoint
    api.add_resource(_CRUD, '/')

This is important particularly in a full flask respository context, but in this case, you'll just need to run the initUsers() function.

initUsers()
Created user with username "Mr. Cards".
Created user with username "Kard Kowntre".
Created user with username "Un Bea Table".

An Alternative Method of Making SQLite Databases

In a previous lesson, we went over using the cursor object in SQLite3. Rather than go over all of that here, this lesson goes over it thoroughly. (You may use this method for the homework below.)

Database Homework

For this assignment, we'd like you to make your own database file as instructed above. Remember, the API file isn't necessary in this case; you'll be focusing on making the model and the init function.

Your database must include these things:

  • A class with at least four attributes (if not the cursor method)
  • Setters and getters for this class (if not the cursor method)
  • Each of the CRUD functions
  • An init function with at least four entries
  • A screenshot showing proof that your SQLite file has been created correctly

Feel free to base your database on the model provided above! Ask our group if you have any questions or concerns.

# If you've already run the db.init_app(app) function while in this notebook,
# don't do it again until you've closed it!

""" database dependencies to support sqliteDB examples """
from random import randrange
from datetime import date
import json

from sqlalchemy.exc import IntegrityError
from werkzeug.security import generate_password_hash, check_password_hash


''' Tutorial: https://www.sqlalchemy.org/library.html#tutorials, try to get into Python shell and follow along '''

# Define the Review class to manage actions in the 'reviews' table
# -- Object Relational Mapping (ORM) is the key concept of SQLAlchemy
# -- a.) db.Model is like an inner layer of the onion in ORM
# -- b.) Review represents data we want to store, something that is built on db.Model
# -- c.) SQLAlchemy ORM is layer on top of SQLAlchemy Core, then SQLAlchemy engine, SQL
class Review(db.Model):
    __tablename__ = 'reviews'  # table name is plural, class name is singular

    # Define the Review schema with "vars" from object
    id = db.Column(db.Integer, primary_key=True)
    _rname = db.Column(db.String(255), unique=False, nullable=False)
    _comment = db.Column(db.Text, unique=False, nullable=False)
    _rating = db.Column(db.Integer, unique=False, nullable=False)
    _uid = db.Column(db.String(255), unique=True, nullable=False)    

    # constructor of a Review object, initializes the instance variables within object (self)
    def __init__(self, rname, comment, rating, uid):
        self._rname = rname    # variables with self prefix become part of the object, 
        self._comment = comment
        self._rating = rating
        self._uid = uid

    # a name getter method, extracts name from object
    @property
    def rname(self):
        return self._rname
    
    # a setter function, allows name to be updated after initial object creation
    @rname.setter
    def rname(self, rname):
        self._rname = rname

    # a comment getter method, extracts comment from object
    @property
    def comment(self):
        return self._comment
    
    # a setter function, allows name to be updated after initial object creation
    @comment.setter
    def comment(self, comment):
        self._comment = comment  

    # a getter method, extracts rating from object
    @property
    def rating(self):
        return self._rating
    
    # a setter function, allows name to be updated after initial object creation
    @rating.setter
    def rating(self, rating):
        self._rating = rating              
    
    # a getter method, extracts uid from object
    @property
    def uid(self):
        return self._uid
    
    # a setter function, allows name to be updated after initial object creation
    @uid.setter
    def uid(self, uid):
        self._uid = uid
        
    # check if uid parameter matches user id in object, return boolean
    def is_uid(self, uid):
        return self._uid == uid
    
  
    # output content using str(object) in human readable form, uses getter
    # output content using json dumps, this is ready for API response
    def __str__(self):
        return json.dumps(self.read())

    # create/add a new record to the table
    # returns self or None on error
    def create(self):
        try:
            # creates a reviewer object from Review(db.Model) class, passes initializers
            print("Inside create")
            db.session.add(self)  # add prepares to persist person object to Reviews table
            db.session.commit()  # SqlAlchemy "unit of work pattern" requires a manual commit
            return self
        except IntegrityError:
            db.session.remove()
            return None

    # read converts self to dictionary
    # returns dictionary
    def read(self):
        # entry = db.session.query(Reviews).get(args["id"])
        # print(id,self.rname,self.uid,self.comment,self.rating)
        return {
            "id": self.id,
            "rname": self.rname,
            "comment":self.comment,
            "rating":self.rating,
            "uid": self.uid            
        }

    # CRUD update: updates comment, rating, uid
    # returns self
    def put(self,id,comment,rating,uid):
        """only updates values with length"""
        print("inside reviews.py update") 
        entry = db.session.query(Review).get(id)
        print("sent request to update record", entry)  
        print(id,comment,rating,uid)
        try:
            if entry: 
                # db.session.update(self)
                entry.comment = comment
                entry.rating = rating
                entry.uid = uid
                print("updated record", entry)
                db.session.commit()
                return entry
            else:
                return {"error": "entry not found"}, 404                
        except Exception as e:
            db.session.rollback()
            return {"error": f"server error: {e}"}, 500            

    # CRUD delete: remove self
    # None
    def delete(id):
        # print("inside reviews.py delete", id) 
        try:
            entry = db.session.query(Review).get(id)
            if entry: 
                db.session.delete(entry)
                db.session.commit()
                print("deleted record", entry)                
                return None
            else:
                return {"error": "entry not found"}, 404                
        except Exception as e:
            db.session.rollback()
            return {"error": f"server error: {e}"}, 500

"""Database Creation and Testing """


# Builds working data for testing
def initReviews():
    with app.app_context():
        """Create database and tables"""
        db.create_all()
        """Tester data for table"""
        u1 = Review(rname='Recipe1', comment='Recipe1 comment', rating=5, uid='toby' )
        u2 = Review(rname='Recipe2', comment='Recipe2 comment', rating=6, uid='niko')
        u3 = Review(rname='Recipe3', comment='Recipe3 comment', rating=3, uid='lex')
        u4 = Review(rname='Recipe4', comment='Recipe4 comment', rating=8, uid='whit')
        u5 = Review(rname='Recipe5', comment='Recipe5 comment', rating=10, uid='jm1021')

        reviews = [u1, u2, u3, u4, u5]

        """Builds sample review/comment(s) data"""
        for review in reviews:
            try:
                review.create()
                print(f'Created review with name "{review.uid}".')
            except IntegrityError:
                '''fails with bad or duplicate data'''
                db.session.remove()
                print(f"Records exist, duplicate email, or error: {review.uid}")
from flask import Blueprint, request, jsonify
from flask_restful import Api, Resource # used for REST API building
from datetime import datetime

review_api = Blueprint('review_api', __name__,
                   url_prefix='/api/reviews')

# API docs https://flask-restful.readthedocs.io/en/latest/api.html
api = Api(review_api)

class ReviewAPI:        
    class _Create(Resource):
        def post(self):
            ''' Read data for json body '''
            body = request.get_json()
            
            ''' Avoid garbage in, error checking '''
            # validate rname
            rname = body.get('rname')
            if rname is None or len(rname) < 2:
                return {'message': f'Name is missing, or is less than 2 characters'}, 200
            # validate uid
            uid = body.get('uid')
            if uid is None or len(uid) < 2:
                return {'message': f'Review ID is missing, or is less than 2 characters'}, 210
            comment = body.get('comment')
            if comment is None or len(comment) < 2:
                return {'message': f'Comment is missing, or is less than 2 characters'}, 220            # validate rname
            rating = body.get('rating')
            if rating is None or len(rating) < 1 or int(rating) > 10:
                return {'message': f'Rating is missing, or is out of range'}, 230

            ''' #1: Key code block, setup REVIEW OBJECT '''
            uo = Review(rname=rname,
                      comment=comment,
                      rating=rating,
                      uid=uid
                      )
            
           
            ''' #2: Key Code block to add review to database '''
            # create review in database
            review = uo.create()
            # success returns json of review
            if review:
                return jsonify(review.read())
            # failure returns error
            return {'message': f'Processed {rname}, either a format error or Review ID {uid} is duplicate'}, 240

    class _Read(Resource):
        def get(self):
            reviews = Review.query.all()    # read/extract all reviews from database
            json_ready = [review.read() for review in reviews]  # prepare output in json
            return jsonify(json_ready)  # jsonify creates Flask response object, more specific to APIs than json.dumps

    class _Delete(Resource):
        def delete(self):
            body = request.get_json()
            id = body.get('id')
            print("inside review.py delete id", id)
            review=Review.delete(id)
            if review:
                reviews = Review.query.all()    # read/extract all reviews from database
                json_ready = [review.read() for review in reviews]  # prepare output in json
                return jsonify(json_ready)  # jsonify creates Flask response object, more specific to APIs than json.dumps               

    class _Update(Resource):
        def put(self):
            print("inside review.py put")
            body = request.get_json()
            id = body.get('id')
            comment = body.get('comment')
            rating = body.get('rating')
            uid = body.get('uid')
            # self.id = id
            # if len(comment) > 0:
            #     self.comment = comment
            # if rating >= 10:
            #     self.rating = rating    
            # if len(uid) > 0:
            #     self.uid = uid 
            print("inside review.py update id", id)
            review=Review.put(self, id,comment,rating,uid)
            # review=Review.put(id, self.comment, self.rating, self.uid)
            if review:
                reviews = Review.query.all()    # read/extract all reviews from database
                json_ready = [review.read() for review in reviews]  # prepare output in json
                return jsonify(json_ready)  # jsonify creates Flask response object, more specific to APIs than json.dumps
              
    # building RESTapi endpoint
    api.add_resource(_Create, '/create')
    api.add_resource(_Read, '/')
    api.add_resource(_Update, '/update')
    api.add_resource(_Delete, '/delete')
initReviews()
Inside create
Created review with name "toby".
Inside create
Created review with name "niko".
Inside create
Created review with name "lex".
Inside create
Created review with name "whit".
Inside create
Created review with name "jm1021".
import sqlite3

def create():
   db_file = 'instance/inventory.db'
   id = input("Enter the id number: ")
   name = input("Enter the item name: ")
   quantity = input("Enter the quantity of items available to sell: ")
   price = input("Enter the price of the item: ")

   connection = sqlite3.connect(db_file)
   cursor = connection.cursor()


   try:
       cursor.execute("INSERT INTO inventory (id, name, quantity, price) VALUES (?, ?, ?, ?)", (id, name, quantity, price))
       connection.commit()
       print(f"{id} has been added to the list of items.")
              
   except sqlite3.Error as error:
       print("Error while inserting record", error)


   cursor.close()
   connection.close()

create()
1 has been added to the list of items.
def read():
    try:
        connection = sqlite3.connect('instance/inventory.db')
        cursor = connection.cursor()

        cursor.execute("SELECT * FROM inventory")
        rows = cursor.fetchall()

        if len(rows) > 0:
            print("List of items to sell:")
            for row in rows:
                print(f"id: {row[0]},\nname: {row[1]},\nquantity: {row[2]},\nprice: {row[3]}")
        else:
            print("There are no items in the list.")

    except sqlite3.Error as error:
        print("Error while connecting to the db_file:", error)

    finally:
        cursor.close()
        connection.close()

read()
List of items to sell:
id: 1,
name: fries,
quantity: 9,
price: 3.0
id: 2,
name: test,
quantity: 4,
price: 4.0
id: 3,
name: testtesttesttesttest,
quantity: 999999,
price: 99.0
id: 5,
name: sandwich,
quantity: 3,
price: 5.0
def update():
    db_file = 'instance/inventory.db'
    connection = sqlite3.connect(db_file)
    cursor = connection.cursor()
    
    try:
        id = input("Enter the id of the item to update: ")
        
        cursor.execute("SELECT * FROM inventory WHERE id=?", (id,))
        record = cursor.fetchone()
        
        if record:
            print("Enter the new information for the item:")
            name = input(f"Name: {record[1]}\nNew name: ")
            quantity = input(f"Quantity: {record[2]}\nNew quantity: ")
            price = input(f"Price: {record[3]}\nNew price: ")
            
            cursor.execute("UPDATE inventory SET name=?, quantity=?, price=? WHERE id=?", (name, quantity, price, id))
            connection.commit()
            
            print(f"{id}'s record has been updated.")
        
        else:
            print(f"No record found for {id}.")
    
    except sqlite3.Error as error:
        print("Error while updating record", error)
    
    cursor.close()
    connection.close()

update()
Enter the new information for the item:
3's record has been updated.
def delete():
    connection = sqlite3.connect('instance/inventory.db')
    cursor = connection.cursor()

    id = input("Enter the id of the item you want to delete: ")

    cursor.execute("SELECT * FROM inventory WHERE id=?", (id,))
    row = cursor.fetchone()

    if row:
        confirm = input(f"Are you sure you want to delete {id}? (y/n): ")
        if confirm.lower() == 'y':
            cursor.execute("DELETE FROM inventory WHERE id=?", (id,))
            connection.commit()
            print(f"{id} has been deleted from the list of items.")
    else:
        print(f"{id} not found in the list of items.")

    
    cursor.close()
    connection.close()

delete()
3 has been deleted from the list of items.
def table():
    operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete")
    if operation.lower() == 'c':
        print("Create Operation")
        create()
    elif operation.lower() == 'r':
        print("Read Operation")
        read()
    elif operation.lower() == 'u':
        print("Update Operation")
        update()
    elif operation.lower() == 'd':
        print("Delete Operation")
        delete()
    elif len(operation)==0:
        return
    else:
        print("Please enter c, r, u, or d")
    table()

try:
    table()
except:
    print("Perform Jupyter 'Run All' prior to starting table")

table()
Create Operation
9 has been added to the list of items.
Read Operation
List of items to sell:
id: 1,
name: fries,
quantity: 9,
price: 3.0
id: 2,
name: test,
quantity: 4,
price: 4.0
id: 5,
name: sandwich,
quantity: 3,
price: 5.0
id: 9,
name: fries,
quantity: 69,
price: 5.0
Update Operation
Enter the new information for the item:
9's record has been updated.
Delete Operation
9 has been deleted from the list of items.

Proof

evidence

Grading

Your submission will be graded based on the following criteria:

  • Filling in the blank throughout the lesson and providing code in the given cells when applicable (0.9)
  • Simulation homework (0.9)
  • Database homework (0.9)

Here are some ideas for ways to increase your score above a 2.7:

  • Make a frontend version of your simulation that can be interacted with on your blog
  • Connect your simulation to the database you create
  • Create a menu that allows a user to make an entry in your database (CRUD functions within it)
  • You can establish a relationship between two classes/tables in your database (see the relationship between the User and Note classes in the Nighthawk Coders flask repository)