Unit 2.4a Using Programs with Data, SQLAlchemy
Using Programs with Data is focused on SQL and database actions. Part A focuses on SQLAlchemy and an OOP programming style,
Database and SQLAlchemy
In this blog we will explore using programs with data, focused on Databases. We will use SQLite Database to learn more about using Programs with Data. Use Debugging through these examples to examine Objects created in Code.
-
College Board talks about ideas like
- Program Usage. "iterative and interactive way when processing information"
- Managing Data. "classifying data are part of the process in using programs", "data files in a Table"
- Insight "insight and knowledge can be obtained from ... digitally represented information"
- Filter systems. 'tools for finding information and recognizing patterns"
- Application. "the preserve has two databases", "an employee wants to count the number of book"
-
PBL, Databases, Iterative/OOP
- Iterative. Refers to a sequence of instructions or code being repeated until a specific end result is achieved
- OOP. A computer programming model that organizes software design around data, or objects, rather than functions and logic
- SQL. Structured Query Language, abbreviated as SQL, is a language used in programming, managing, and structuring data
"""
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)
""" 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 '''
# 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 User(db.Model):
__tablename__ = 'review' # table name is plural, class name is singular
# Define the User 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 User 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())
# 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
print("Inside create")
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):
# entry = db.session.query(Users).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 users.py update")
entry = db.session.query(User).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
# user.verified = True
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 users.py delete", id)
try:
entry = db.session.query(User).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
Initial Data
Uses SQLALchemy db.create_all() to initialize rows into sqlite.db
- Comment on how these work?
- Create All Tables from db Object - creates the tables using the information in the object
- User Object Constructors - Sets the restrictions for what the info within the object should be / how it should be formatted
- Try / Except - sets a procedure for what to do in case of an error
def initReviews():
with app.app_context():
"""Create database and tables"""
db.create_all()
"""Tester data for table"""
u1 = User(rname='Recipe1', comment='Recipe1 comment', rating=5, uid='toby' )
u2 = User(rname='Recipe2', comment='Recipe2 comment', rating=6, uid='niko')
u3 = User(rname='Recipe3', comment='Recipe3 comment', rating=3, uid='lex')
u4 = User(rname='Recipe4', comment='Recipe4 comment', rating=8, uid='whit')
u5 = User(rname='Recipe5', comment='Recipe5 comment', rating=10, uid='jm1021')
users = [u1, u2, u3, u4, u5]
"""Builds sample user/comment(s) data"""
for user in users:
try:
user.create()
except IntegrityError:
'''fails with bad or duplicate data'''
db.session.remove()
print(f"Records exist, duplicate email, or error: {user.uid}")
initReviews()
Check for given Credentials in users table in sqlite.db
Use of ORM Query object and custom methods to identify user to credentials uid and password
- Comment on purpose of following
- User.query.filter_by - filters by whatever the set filter is
- user.password - cross-references with the currently set password
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):
# query email and return user record
user = find_by_uid(uid)
if user == None:
return False
return True
check_credentials("toby")
Create a new User in table in Sqlite.db
Uses SQLALchemy and custom user.create() method to add row.
- Comment on purpose of following
- user.find_by_uid() and try/except - searches for a user by the uid is also set to handle error cases.
- user = User(...) - makes a new user object with the following properties
- user.dob and try/except - gets the user's birthday, handles error cases in terms of misinputs
- user.create() and try/except - makes a new user and adds to the user object, handles error cases using try and except.
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
rname = input("Enter the recipe you are reviewing:")
comment = input("Enter your review:")
rating = input("Enter your rating out of 10:")
uid = input("Enter your Username:")
# Initialize User object before date
uo = User(rname=rname,
comment=comment,
rating=rating,
uid=uid
)
# create user.dob, fail with today as dob
# write object to database
with app.app_context():
try:
user = uo.create()
print("Created\n", object.read())
except: # error raised if object not created
print("Unknown error uid {uid}")
create()
def read():
with app.app_context():
table = User.query.all()
json_ready = [user.read() for user in table] # "List Comprehensions", for each user add user.read() to list
return json_ready
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
rname = input("Enter the recipe you are reviewing:")
comment = input("Enter your review:")
rating = input("Enter your rating out of 10:")
uid = input("Enter your Username:")
# Initialize User object before date
uo = User(rname=rname,
comment=comment,
rating=rating,
uid=uid
)
# write object to database
with app.app_context():
try:
user = uo.create()
print("Created\n", object.read())
except: # error raised if object not created
print("Unknown error uid {uid}")
update()
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 review 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()