Unit 2.4a Hacks
Using Programs with Data is focused on SQL and database actions. Part A focuses on SQLAlchemy and an OOP programming style,
"""
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)
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, unique=True, primary_key=True)
_brand = db.Column(db.String(255), unique=False, nullable=False)
_color = db.Column(db.Integer, unique=False, nullable=False)
_powersource = db.Column(db.String(255), unique=False, nullable=False)
_type = db.Column(db.String(255), unique=False, nullable=False)
# constructor of a User object, initializes the instance variables within object (self)
def __init__(self, brand, color, type, powersource):
self._brand = brand
self._color = color
self._powersource = powersource
self._type = type
# gets the brand the car
@property
def brand(self):
return self._brand
# a setter function, allows brand to be updated after initial object creation
@brand.setter
def brand(self, brand):
self._brand = brand
# gets the color of the car
@property
def color(self):
return self._color
# a setter function, allows color to be updated after initial object creation
@color.setter
def color(self, color):
self._color = color
# gets the type of the manufacturer or the car
@property
def type(self):
return self._type
# a setter function, allows type to be updated after initial object creation
@type.setter
def type(self, type):
self._type = type
# a powersource getter
@property
def powersource(self):
return self._powersource
# a setter function to set the car's powersource
@powersource.setter
def powersource(self, powersource):
self._powersource = powersource
# CRUD read converts self to dictionary
# returns dictionary
def read(self):
return {
"id": self.id,
"brand" : self.brand,
"color" : self.color,
"powersource" : self.powersource,
"type" : self.type,
}
def update(self, brand="", color="", powersource="", type=""):
"""only updates values with length"""
if len(brand) > 0:
self.brand = brand
if len(color) > 0:
self.color = color
if len(powersource) > 0:
self.powersource = powersource
if len(type) > 0:
self.type = type
db.session.add(self) # performs update when id exists\n",
db.session.commit()
return self
def delete(self):
db.session.delete(self)
db.session.commit()
return None
def initCars():
with app.app_context():
"""Create database and tables"""
db.create_all()
"""Tester data for table"""
c1 = Car(brand='Acura', color='gray', powersource='ice', type='suv')
c2 = Car(brand='Hyundai', color='red', powersource='ice', type='sedan')
c3 = Car(brand='Mazda', color='white', powersource='ice', type='sedan')
c4 = Car(brand='Honda', color='gray', powersource='ice', type='suv')
c5 = Car(brand='Dodge', color='black', powersource='ice', type='suv')
c6 = Car(brand='Toyota', color='white', powersource='ice', type='truck')
c7 = Car(brand='Hyundai', color='blue', powersource='ice', type='sedan')
c8 = Car(brand='Chevrolet', color='gray', powersource='ice', type='truck')
c9 = Car(brand='Jeep', color='gray', powersource='ice', type='suv')
c10 = Car(brand='Nissan', color='silver', powersource='ice', type='sedan')
c11 = Car(brand='Lexus', color='black', powersource='ice', type='sedan')
c12 = Car(brand='Kia', color='red', powersource='ice', type='suv')
c13 = Car(brand='Mazda', color='red', powersource='ice', type='truck')
c14 = Car(brand='Ford', color='white', powersource='ice', type='sedan')
c15 = Car(brand='Kia', color='red', powersource='ice', type='truck')
c16 = Car(brand='Ford', color='gray', powersource='ice', type='suv')
c17 = Car(brand='Jeep', color='red', powersource='ice', type='truck')
c18 = Car(brand='Toyota', color='red', powersource='electric', type='suv')
c19 = Car(brand='Kia', color='silver', powersource='ice', type='truck')
c20 = Car(brand='Honda', color='white', powersource='ice', type='suv')
c21 = Car(brand='Hyundai', color='white', powersource='ice', type='sedan')
c22 = Car(brand='Chevrolet', color='white', powersource='ice', type='suv')
c23 = Car(brand='Jeep', color='white', powersource='ice', type='suv')
c24 = Car(brand='BMW', color='gray', powersource='ice', type='sedan')
c25 = Car(brand='Ferrari', color='yellow', powersource='ice', type='sports')
c26 = Car(brand='Tesla', color='red', powersource='electric', type='suv')
c27 = Car(brand='Tesla', color='blue', powersource='electric', type='suv')
c28 = Car(brand='Ford', color='white', powersource='electric', type='truck')
c29 = Car(brand='Ford', color='blue', powersource='electric', type='truck')
c30 = Car(brand='Audi', color='black', powersource='electric', type='suv')
c31 = Car(brand='Ferrari', color='red', powersource='electric', type='sports')
c32 = Car(brand='Mercedes', color='silver', powersource='electric', type='sedan')
c33 = Car(brand='Mazda', color='silver', powersource='electric', type='suv')
c34 = Car(brand='Nissan', color='blue', powersource='electric', type='suv')
c35 = Car(brand='Subaru', color='red', powersource='electric', type='suv')
cars = [c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32, c33, c34, c35]
"""Builds sample car/note(s) data"""
for user in cars:
try:
'''add car to table'''
object = Car.create()
print(f"Created new car {object.Car}")
except: # error raised if object nit created
'''fails with bad or duplicate data'''
print(f"Records exist car {user.Car}, or error.")
initCars()
def createCar():
uid = input("Enter your car id:")
try:
print("Found\n", car.read())
return
except:
pass # keep going
# request value that ensure creating valid object
brand = input("What brand is the car?")
color = input("What color is the car?")
powersource = input("What is the car's powersource?")
type = input("What type of car is it?")
# Initialize User object before date
car = Car(brand=brand,
color=color,
powersource=powersource,
type=type
)
# write object to database
with app.app_context():
try:
object = car.create()
print("Created\n", object.read())
except: # error raised if object not created
print("Unknown error powersource {uid}")
createCar()
def readCar():
with app.app_context():
table = Car.query.all()
json_ready = [car.read() for car in table] # "List Comprehensions", for each car add car.read() to list
return json_ready
readCar()
def updateCar(uid, new_brand, new_color, new_powersource, new_type):
with app.app_context():
car = db.session.query(Car).filter_by(_uid=uid).first()
try:
print("Found\n", car.read())
car.update(new_brand, new_color, new_powersource, new_type)
return
except:
pass # keep going
new_brand = input("Enter new brand:")
new_color = input("Enter new color:")
new_powersource = input("Enter new powersource:")
new_type = input("Enter new type:")
updateCar(new_brand, new_color, new_powersource, new_type)
def deleteCar(uid):
with app.app_context():
car = db.session.query(Car).filter_by(_uid=uid).first()
try:
print("Found\n", car.read())
car.delete()
return
except:
pass # keep going
uid = input("Enter your car uid:")
deleteCar(uid)