week 26 hacks

In the Blog add notes and observations on each code cell.

cell block number 1

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# Create a Flask application object
app = Flask(__name__)

# Specify the location of the database and configure SQLAlchemy
database = 'sqlite:///files/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()

# Initialize the SQLAlchemy app with the Flask app
db.init_app(app)

cell block number 2

import datetime
from datetime import datetime
import json

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


# Define the User class to manage actions in the 'users' table
class User(db.Model):
    __tablename__ = 'users'  # Set the name of the table to 'users'

    # Define the User schema with columns for the table
    id = db.Column(db.Integer, primary_key=True)  # Column for the primary key (integer)
    _name = db.Column(db.String(255), unique=False, nullable=False)  # Column for name (string)
    _uid = db.Column(db.String(255), unique=True, nullable=False)  # Column for user id (string)
    _password = db.Column(db.String(255), unique=False, nullable=False)  # Column for password (string)
    _dob = db.Column(db.Date)  # Column for date of birth (date)

    # Constructor for the User object, initializes instance variables
    def __init__(self, name, uid, password="123qwerty", dob=datetime.today()):
        self._name = name
        self._uid = uid
        self.set_password(password)
        if isinstance(dob, str):  # Check if dob is a string, set to today's date if true
            dob = date=datetime.today()
        self._dob = dob

    # Getter method for the name variable
    @property
    def name(self):
        return self._name
    
    # Setter method for the name variable
    @name.setter
    def name(self, name):
        self._name = name
    
    # Getter method for the uid variable
    @property
    def uid(self):
        return self._uid
    
    # Setter method for the uid variable
    @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
    
    # Getter method for the password variable, only shows the first 10 characters
    @property
    def password(self):
        return self._password[0:10] + "..."

    # Setter method for the password variable, encrypts the password using SHA256 hashing algorithm
    def set_password(self, password):
        """Create a hashed password."""
        self._password = generate_password_hash(password, method='sha256')

    # Check if password parameter matches stored/encrypted password, return boolean
    def is_password(self, password):
        """Check against hashed password."""
        result = check_password_hash(self._password, password)
        return result
    
    # Getter method for the dob variable, returns the dob as a formatted string
    @property
    def dob(self):
        dob_string = self._dob.strftime('%m-%d-%Y')
        return dob_string
    
    # Setter method for the dob variable, sets the dob to today's date if it is a string
    @dob.setter
    def dob(self, dob):
        if isinstance(dob, str):     
            dob = date=datetime.today()
        self._dob = dob
    
    # Getter method for the age variable, calculates the age based on dob
    @property
    def age(self):
        today = datetime.today()
        return today.year - self._dob.year - ((today.month, today.day) < (self._dob.month, self._dob.day))
    
    # Convert the User object to a dictionary
    def read(self):
        return {
            "id": self.id,
            "name": self.name

code block number 3

# Builds working data for testing
def initUsers():
    with app.app_context():
        # Create database and tables
        db.create_all()

        # Add tester data to table
        u1 = User(name='Thomas Edison', uid='toby', password='123toby', dob=datetime(1847, 2, 11))
        u2 = User(name='Nikola Tesla', uid='niko', password='123niko')
        u3 = User(name='Alexander Graham Bell', uid='lex', password='123lex')
        u4 = User(name='Eli Whitney', uid='whit', password='123whit')
        u5 = User(name='Indiana Jones', uid='indi', dob=datetime(1920, 10, 21))
        u6 = User(name='Marion Ravenwood', uid='raven', dob=datetime(1921, 10, 21))

        # Add users to a list
        users = [u1, u2, u3, u4, u5, u6]

        # Build sample user/note(s) data
        for user in users:
            try:
                # Add user to table
                object = user.create()
                print(f"Created new uid {object.uid}")
            except:
                # Handle error if object is not created
                print(f"Records exist uid {user.uid}, or error.")
                
# Call initUsers function to create and populate the database
initUsers()

code block number 4

# Builds working data for testing
def initUsers():
    with app.app_context():
        """Create database and tables"""
        db.create_all()
        """Tester data for table"""
        u1 = User(name='Thomas Edison', uid='toby', password='123toby', dob=datetime(1847, 2, 11))
        u2 = User(name='Nikola Tesla', uid='niko', password='123niko')
        u3 = User(name='Alexander Graham Bell', uid='lex', password='123lex')
        u4 = User(name='Eli Whitney', uid='whit', password='123whit')
        u5 = User(name='Indiana Jones', uid='indi', dob=datetime(1920, 10, 21))
        u6 = User(name='Marion Ravenwood', uid='raven', dob=datetime(1921, 10, 21))


        users = [u1, u2, u3, u4, u5, u6]

        """Builds sample user/note(s) data"""
        for user in users:
            try:
                '''add user to table'''
                object = user.create()
                print(f"Created new uid {object.uid}")
            except:  # error raised if object nit created
                '''fails with bad or duplicate data'''
                print(f"Records exist uid {user.uid}, or error.")
                
initUsers() 

code block number 5

def find_by_uid(uid):
    with app.app_context():
        user = User.query.filter_by(_uid=uid).first()
    return user # returns user object

# Check credentials by finding user and verify password
def check_credentials(uid, password):
    # query email and return user record
    user = find_by_uid(uid)
    if user == None:
        return False
    if (user.is_password(password)):
        return True
    return False
        
#check_credentials("indi", "123qwerty")

code block number 6

def create():
    # optimize user time to see if uid exists
    uid = input("Enter your user id:")
    user = find_by_uid(uid)
    try:
        print("Found\n", user.read())
        return
    except:
        pass # keep going
    
    # request value that ensure creating valid object
    name = input("Enter your name:")
    password = input("Enter your password")
    
    # Initialize User object before date
    user = User(name=name, 
                uid=uid, 
                password=password
                )
    
    # create user.dob, fail with today as dob
    dob = input("Enter your date of birth 'YYYY-MM-DD'")
    try:
        user.dob = datetime.strptime(dob, '%Y-%m-%d').date()
    except ValueError:
        user.dob = datetime.today()
        print(f"Invalid date {dob} require YYYY-mm-dd, date defaulted to {user.dob}")
           
    # write object to database
    with app.app_context():
        try:
            object = user.create()
            print("Created\n", object.read())
        except:  # error raised if object not created
            print("Unknown error uid {uid}")
        
create()

Change blog to your own database.

"""
These imports define the key objects
"""

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

"""
These object and definitions are used throughout the Jupyter Notebook.
"""

# 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 databaseapp.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)
""" database dependencies to support sqlite examples """
import datetime
from datetime import datetime
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 a Python shell and follow along '''
class Phone(db.Model):
    __tablename__ = 'Phones'  # table name is plural, class name is singular

    id = db.Column(db.Integer, primary_key=True)
    _company = db.Column(db.String(255), unique=False, nullable=False) #_name
    _model = db.Column(db.String(255), unique=True, nullable=False) #_uid
    _price = db.Column(db.String(255), unique=False, nullable=False) # _password
    _dob = db.Column(db.Date) #_dob

    def __init__(self, company, model, price, dob=datetime.today()):
        self._company = company    # variables with self prefix become part of the object, 
        self._model = model
        self._price = price
        # self.set_password(password)
        if isinstance(dob, str):  # not a date type     
            dob = date=datetime.today()
        self._dob = dob

    @property
    def company(self):
        return self._company
    
    @company.setter
    def company(self, company):
        self._company = company
    
    @property
    def model(self):
        return self._model
    
    @model.setter
    def model(self, model):
        self._model = model
        
    def is_model(self, model):
        return self._model == model
    
    @property
    def price(self):
        return self._price
    
    @price.setter
    def price(self, price):
        self._price = price
    
    # @property
    # def password(self):
    #     return self._password[0:10] + "..." # because of security only show 1st characters

    # # update password, this is conventional setter
    # def set_password(self, password):
    #     """Create a hashed password."""
    #     self._password = generate_password_hash(password, method='sha256')

    # # check password parameter versus stored/encrypted password
    # def is_password(self, password):
    #     """Check against hashed password."""
    #     result = check_password_hash(self._password, password)
    #     return result
    
    # dob property is returned as string, to avoid unfriendly outcomes
    @property
    def dob(self):
        dob_string = self._dob.strftime('%m-%d-%Y')
        return dob_string
    
    @dob.setter
    def dob(self, dob):
        if isinstance(dob, str):  # not a date type     
            dob = date=datetime.today()
        self._dob = dob
    
    @property
    def age(self):
        today = datetime.today()
        return today.year - self._dob.year - ((today.month, today.day) < (self._dob.month, self._dob.day))
    
    def __str__(self):
        return json.dumps(self.read())

    def create(self):
        try:
            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

    def read(self):
        return {
            "id": self.id,
            "company": self.company,
            "model": self.model,
            "price": self.price,
            "dob": self.dob,
            "age": self.age,
        }

    def update(self, company="", model="", price=""):
        """only updates values with length"""
        if len(company) > 0:
            self.company = company
        if len(model) > 0:
            self.model = model
        if len(price) > 0:
            self.price = price
        db.session.commit()
        db.session.add(self)
        return self

    def delete(self):
        db.session.delete(self)
        db.session.commit()
        return None
"""Database Creation and Testing """


# Builds working data for testing
def initPhones():
    with app.app_context():
        """Create database and tables"""
        db.create_all()
        """Tester data for table"""
        p1 = Phone(company='Apple', model='iPhone 14', price='200')
        p2 = Phone(company='Apple', model='iPhone 14 Pro', price='150')
        p3 = Phone(company='Samsung', model='Galaxy S23', price='100')
        p4 = Phone(company='LG', model='Wing', price='300')
        p5 = Phone(company='Motorola', model='Razr', price='250')
        p6 = Phone(company='Google', model='Pixel 7', price='50')

        phones = [p1, p2, p3, p4, p5, p6]

        """Builds sample user/note(s) data"""
        for phone in phones:
            try:
                '''add user to table'''
                object = phone.create()
                print(f"Created new uid {object.model}")
            except:  # error raised if object nit created
                '''fails with bad or duplicate data'''
                print(f"Records exist uid {phone.model}, or error.")
                
initPhones()
Records exist uid iPhone 14, or error.
Records exist uid iPhone 14 Pro, or error.
Records exist uid Galaxy S23, or error.
Records exist uid Wing, or error.
Records exist uid Razr, or error.
Records exist uid Pixel 7, or error.
def find_by_model(model):
    with app.app_context():
        phone = Phone.query.filter_by(_model=model).first()
    return phone

Additional CRUD operations

Create

def create():
    # optimize user time to see if uid exists
    model = input("Enter your model:")
    phone = find_by_model(model)
    try:
        print("Found\n", phone.read())
        return
    except:
        pass # keep going
    
    # request value that ensure creating valid object
    company = input("Enter the company:")
    price = input("Enter the price")
    
    # Initialize User object before date
    phone = Phone(company=company, 
                model=model, 
                price=price,
                )
    
    # create user.dob, fail with today as dob
    # dob = input("Enter your date of birth 'YYYY-MM-DD'")
    # try:
    #     user.dob = datetime.strptime(dob, '%Y-%m-%d').date()
    # except ValueError:
    #     user.dob = datetime.today()
    #     print(f"Invalid date {dob} require YYYY-mm-dd, date defaulted to {user.dbo}")
           
    # write object to database
    with app.app_context():
        try:
            object = phone.create()
            print("Created\n", object.read())
        except:  # error raised if object not created
            print("Unknown error uid {uid}")
        
create()
Created
 {'id': 8, 'company': 'apple', 'model': 'ipheob', 'price': '', 'dob': '03-21-2023', 'age': 0}

Read:

def read():
    with app.app_context():
        table = Phone.query.all()
    json_ready = [phone.read() for phone in table] # each user adds user.read() to list
    return json_ready

read()
[{'id': 1,
  'company': 'Apple',
  'model': 'iPhone 14',
  'price': '200',
  'dob': '03-20-2023',
  'age': 0},
 {'id': 2,
  'company': 'Apple',
  'model': 'iPhone 14 Pro',
  'price': '150',
  'dob': '03-20-2023',
  'age': 0},
 {'id': 3,
  'company': 'Samsung',
  'model': 'Galaxy S23',
  'price': '100',
  'dob': '03-20-2023',
  'age': 0},
 {'id': 4,
  'company': 'LG',
  'model': 'Wing',
  'price': '300',
  'dob': '03-20-2023',
  'age': 0},
 {'id': 5,
  'company': 'Motorola',
  'model': 'Razr',
  'price': '250',
  'dob': '03-20-2023',
  'age': 0},
 {'id': 6,
  'company': 'Google',
  'model': 'Pixel 7',
  'price': '50',
  'dob': '03-20-2023',
  'age': 0},
 {'id': 7,
  'company': 'Applw',
  'model': 'iPhone XR',
  'price': '1,200',
  'dob': '03-20-2023',
  'age': 0}]

Delete:

def delete_by_company(): # makes a new function called delete_by_uid
    model = input("Enter uid of user to be deleted.") # prompts the user to enter the uid
    user = find_by_model(model)  # using previous function to locate user by inputted id
    with app.app_context():
        try:
            object = user.delete() 
            print(f"User with uid --{model}-- has been deleted. ")
            db = read()
            print(db)
        except:  # error raised if object not found
           (f"No user with uid {model} was found.")
        
delete_by_company()

understand debugging

image

unit 2.4b hacks

observations

code block 1

import sqlite3

database = 'instance/sqlite.db' # this is location of database

def schema():
    
    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL queries
    cursor = conn.cursor()
    
    # Fetch results of Schema
    results = cursor.execute("PRAGMA table_info('users')").fetchall()

    # Print the results
    for row in results:
        print(row)

    # Close the database connection
    conn.close()
    
schema()

code block 2

import sqlite3

def read():
    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL queries
    cursor = conn.cursor()
    
    # Execute a SELECT statement to retrieve data from a table
    results = cursor.execute('SELECT * FROM users').fetchall()

    # Print the results
    if len(results) == 0:
        print("Table is empty")
    else:
        for row in results:
            print(row)

    # Close the cursor and connection objects
    cursor.close()
    conn.close()
    
read()

code block 3

import sqlite3

def create():
    name = input("Enter your name:")
    uid = input("Enter your user id:")
    password = input("Enter your password")
    dob = input("Enter your date of birth 'YYYY-MM-DD'")
    
    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL commands
    cursor = conn.cursor()

    try:
        # Execute an SQL command to insert data into a table
        cursor.execute("INSERT INTO users (_name, _uid, _password, _dob) VALUES (?, ?, ?, ?)", (name, uid, password, dob))
        
        # Commit the changes to the database
        conn.commit()
        print(f"A new user record {uid} has been created")
                
    except sqlite3.Error as error:
        print("Error while executing the INSERT:", error)


    # Close the cursor and connection objects
    cursor.close()
    conn.close()
    
#create()

code block 4

import sqlite3

def update():
    uid = input("Enter user id to update")
    password = input("Enter updated password")
    if len(password) < 2:
        message = "hacked"
        password = 'gothackednewpassword123'
    else:
        message = "successfully updated"

    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL commands
    cursor = conn.cursor()

    try:
        # Execute an SQL command to update data in a table
        cursor.execute("UPDATE users SET _password = ? WHERE _uid = ?", (password, uid))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No uid {uid} was not found in the table")
        else:
            print(f"The row with user id {uid} the password has been {message}")
            conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the UPDATE:", error)
        
    
    # Close the cursor and connection objects
    cursor.close()
    conn.close()
    
#update()

code block 5

import sqlite3

def delete():
    uid = input("Enter user id to delete")

    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL commands
    cursor = conn.cursor()
    
    try:
        cursor.execute("DELETE FROM users WHERE _uid = ?", (uid,))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No uid {uid} was not found in the table")
        else:
            # The uid was found in the table and the row was deleted
            print(f"The row with uid {uid} was successfully deleted")
        conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the DELETE:", error)
        
    # Close the cursor and connection objects
    cursor.close()
    conn.close()
    
#delete()

code block 6

def menu():
    operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete or (S)chema")
    if operation.lower() == 'c':
        create()
    elif operation.lower() == 'r':
        read()
    elif operation.lower() == 'u':
        update()
    elif operation.lower() == 'd':
        delete()
    elif operation.lower() == 's':
        schema()
    elif len(operation)==0: # Escape Key
        return
    else:
        print("Please enter c, r, u, or d") 
    menu() # recursion, repeat menu
        
try:
    menu() # start menu
except:
    print("Perform Jupyter 'Run All' prior to starting menu")

in this implementation, do you see procedural abstraction?

yes, in this implementation, i do see a procedural abstraction. using procedural abstraction, the code can write code that is easier to read and maintain. unlike the previous code, this did not give me a headache.

  • Recalling the College Board criteria, data abstraction is essentially representing something (i.e a program) in a much more simplified, condensed method while hiding its more internal functions
  • Looking at this implementation, I do see data abstraction in this implementation. The implementation hides the details of the underlying database operations from the user, providing a simple interface for performing basic CRUD (Create, Read, Update, Delete) operations
  • Regarding debugging, one possible example is if the user enters invalid input (e.g., a non-existent uid when updating or deleting a user). An example would be the implementation catches the exception raised by the database operation and prints an error message to the user
  • The error message provides a high-level explanation of the problem ("No uid was found in the table"), without revealing the underlying implementation details. This is an example of data abstraction, as the implementation is hiding the details of the database operation (in this case, the SQL query) from the user and providing a simplified, high-level interface for working with the data.

note: need vpn to view these images.

image

big idea 2

image