"""
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 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 code sets up a Flask app with an SQLAlchemy database. The SQLAlchemy object creates an interface to connect the Flask app with the SQLite database.

""" database dependencies to support sqlite examples """
import datetime
from datetime import datetime
import json

from sqlalchemy.exc import IntegrityError

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

# Define the User class to manage actions in the 'users' 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.) User 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 Car(db.Model):
    __tablename__ = 'cars'  # table name is plural, class name is singular

    # Define the User schema with "vars" from object
    id = db.Column(db.Integer, primary_key=True)
    _name = db.Column(db.String(255), unique=False, nullable=False)
    _uid = db.Column(db.String(255), unique=True, nullable=False)
    _dreamcar = db.Column(db.String(255), unique=False, nullable=False)
    _car = db.Column(db.String(255), unique=False, nullable=False)
    _chargetime = db.Column(db.Integer, primary_key=False)

    # constructor of a User object, initializes the instance variables within object (self)
    def __init__(self, name, uid, dreamcar, car, chargetime):
        self._name = name    # variables with self prefix become part of the object, 
        self._uid = uid
        self._dreamcar = dreamcar
        self._car = car
        self._chargetime = chargetime

    # a name getter method, extracts name from object
    @property
    def name(self):
        return self._name
    
    # a setter function, allows name to be updated after initial object creation
    @name.setter
    def name(self, name):
        self._name = name
    
    # a getter method, extracts uid from object
    @property
    def uid(self):
        return self._uid
    
    # a setter function, allows uid 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
    
    # a getter method, extracts dreamcar from object
    @property
    def dreamcar(self):
        return self._dreamcar
    
    # a setter function, allows dreamcar to be updated after initial object creation
    @dreamcar.setter
    def dreamcar(self, dreamcar):
        self._dreamcar = dreamcar

    # a getter method, extracts car from object
    @property
    def car(self):
        return self._car

    # a setter function, allows car to be updated after initial object creation
    @car.setter
    def car(self, car):
        self._car = car
    
    # a getter method, extracts chargetime from object
    @property
    def chargetime(self):
        return self._chargetime
    
    # a setter function, allows car to be updated after initial object creation
    @chargetime.setter
    def chargetime(self, chargetime):
        self._chargetime = chargetime
    
    # output content using str(object) is in human readable form
    # 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,
            "name": self.name,
            "uid": self.uid,
            "dreamcar": self.dreamcar,
            "chargetime": self.chargetime,
            "car": self.car,
        }

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

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

This code defines a SQLAlchemy class called Car with CRUD (Create, Read, Update, Delete) functionality to manage actions on a SQLite database table called cars. The class contains instance variables for each column in the cars table, getter and setter methods for each instance variable, and methods to translate between the Python objects and the database. It defines a Python class called Car that represents a SQLite database table with the same name. The class extends the db.Model object from the SQLAlchemy package to provide ORM functionality. The ORM is used to bridge the gap between a relational database and an object-oriented programming language like Python.

"""Database Creation and Testing """


# Builds working data for testing
def initCars():
    with app.app_context():
        """Create database and tables"""
        db.create_all()
        """Tester data for table"""
        u1 = Car(name='Thomas Edison', uid='toby', dreamcar='Tesla Model Y', chargetime='7 Hours', car='Tesla Model X')
        u2 = Car(name='Nikola Tesla', uid='niko', dreamcar='Lucid Air', chargetime='10 Hours', car='Tesla Model S')
        u3 = Car(name='Alexander Graham Bell', uid='lex', dreamcar='Tesla Model X', chargetime='7 Hours', car='Honda Civic 2020')
        u4 = Car(name='Eli Whitney', uid='whit', dreamcar='Tesla Model S', chargetime='7 Hours', car='Lucid Air')
        u5 = Car(name='Indiana Jones', uid='indi', dreamcar='Tesla Model 3', chargetime='7 Hours', car='Tesla Model S')
        u6 = Car(name='Marion Ravenwood', uid='raven', dreamcar='NIO ec6', chargetime='9 Hours', car='Tesla Model 3')


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

    
        for car in cars:
            try:
                object = car.create()
                print(f"Created new uid {object.uid}")
            except:  # error raised if object nit created
                print(f"Records exist uid {car.uid}, or error.")
                
initCars()

The code creates and populates a database with tester data for car objects. The initCars() function first creates a list of car objects, including properties such as name, uid, dreamcar, chargetime, and car. It then uses a for loop and try-except statement to create new objects for each car in the list by calling the create() method for each car object.

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

# Check credentials by finding user and verify password
def check_credentials(uid):
    # query email and return user record
    user = find_by_uid(uid)
    if user == None:
        return False
    return True
        
check_credentials("toby")

The check_credentials function uses the find_by_uid function to check the existence of a user in the database. It takes the user ID as an argument and returns a boolean value indicating whether or not the user exists.

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:")
    dreamcar = input("Enter your dream electric car:")
    car = input("Enter your car:")
    chargetime = input("Enter the charge time of your dream electric car:")
    
    # Initialize User object before date
    user = Car(name=name, 
                uid=uid, 
                dreamcar=dreamcar,
                car=car,
                chargetime=chargetime
                )
    
    # create user.dob, fail with today as 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()

The create() function in this code involves the following steps: - The user is requested to input their user id. - The find_by_uid(uid) method is called to check if the user object already exists. - If the object exists, the method read() is called on it to display it to the user, and the function exits. - If the object does not exist, the user is requested to input their name, dream electric car, car, and charge time of their dream electric car. - A new user object with the input values is created. - The method create() is called on the user to write it to the database. - If there is an error creating the user object, an error message is printed.

def read():
    with app.app_context():
        table = Car.query.all()
    json_ready = [user.read() for user in table] # "List Comprehensions", for each user add user.read() to list
    return json_ready

read()

The code is using the SQLAlchemy package to connect to a database and query data from the Car table. The table data is then converted to a list of JSON objects using list comprehension, which is a more succinct way of generating a list. The created method is named read().

def update():
    # optimize user time to see if uid exists
    uid = input("Enter your user id:")
    user = find_by_uid(uid)
    if user != None:
        pass
    else:
        print(f"No user id {uid} found")
        return
    name = input("Enter your name:")
    chargetime = input("Enter the charge time of your dream electric car:")
    car = input("Enter your car:")
    
    # Initialize User object before date
    user = Car(name=name, 
                uid=uid, 
                chargetime=chargetime,
                car=car,
                )
    # write object to database
    with app.app_context():
        try:
            object = user.update()
            print("Updated\n", object.read())
        except:  # error raised if object not created
            print("Unknown error uid {uid}")
        
update()

The code prompts a user to input their user ID, name, car model, and dream electric car charge time. It then creates an object of the Car class with these attributes and updates its corresponding record in a database. If the user ID does not exist, the program returns an error message.

import sqlite3

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

def delete():
    id = input("Enter 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 cars WHERE id = ?", (id))
        if cursor.rowcount == 0:
            # The id was not found in the table
            print(f"No id {id} was not found in the table")
        else:
            # The id was found in the table and the row was deleted
            print(f"The row with id {id} was successfully deleted")
        conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the DELETE:", error)
    finally:
        conn.commit()
        conn.close()

delete()

In this code, the delete() function connects to a SQLite database using sqlite3.connect(database), where database is the path of the database. The function then asks the user to input an ID, and uses that ID to delete a row from a table called cars in the database. The execute() function of the cursor object executes an SQL command that deletes a row from the cars table. The ? character in the SQL command is a parameter placeholder that is replaced by the value of the id variable when the command is execute. The commit() function saves the changes made to the database, and the close() function closes the connection.