Procedural abstraction?

  • There is lots of procedural abstraction in both 2.4a and 2.4b
  • Everywhere where a procedure is named is an example of procedural abstraction. Naming helps keep things clean and easy and can be re-used later
  • The same procedure being used or called more than once is also an example of procedural abstraction and this happens multiple times.

Debugging Examples

"""
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:///customer.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 customer(db.Model):
    __tablename__ = 'customers'  # table name is plural, class name is singular

    # Define the User schema with "vars" from object
    customerid = db.Column(db.Integer, primary_key=True)
    _customername = db.Column(db.String(255), unique=False, nullable=False)
    _customeruid = db.Column(db.String(255), unique=True, nullable=False)
    _customerpassword = db.Column(db.String(255), unique=False, nullable=False)
    _state = db.Column(db.Date)

    # constructor of a User object, initializes the instance variables within object (self)
    def __init__(self, customername, customeruid, customerpassword="123qwerty", state=datetime.today()):
        self._customername = customername    # variables with self prefix become part of the object, 
        self._customeruid = customeruid
        self.set_password(customerpassword)
        if isinstance(state, str):  # not a date type     
            state = state=datetime.today()
        self._state = state

    # a name getter method, extracts name from object
    @property
    def customername(self):
        return self._customername
    
    # a setter function, allows name to be updated after initial object creation
    @customername.setter
    def customername(self, customername):
        self._customername = customername
    
    # a getter method, extracts uid from object
    @property
    def customeruid(self):
        return self._customeruid
    
    # a setter function, allows uid to be updated after initial object creation
    @customeruid.setter
    def uid(self, customeruid):
        self._customeruid = customeruid
        
    # check if uid parameter matches user id in object, return boolean
    def is_uid(self, customeruid):
        return self._customeruid == customeruid
    
    @property
    def customerpassword(self):
        return self._customerpassword[0:10] + "..." # because of security only show 1st characters

    # update password, this is conventional method used for setter
    def set_customerpassword(self, customerpassword):
        """Create a hashed password."""
        self._customerpassword = generate_password_hash(customerpassword, method='sha256')

    # check password parameter against stored/encrypted password
    def is_customerpassword(self, customerpassword):
        """Check against hashed password."""
        result = check_password_hash(self._customerpassword, customerpassword)
        return result
    
    # dob property is returned as string, a string represents date outside object
    @property
    def state(self):
        state_string = self._state.strftime('%m-%d-%Y')
        return state_string
    
    # dob setter, verifies date type before it is set or default to today
    @state.setter
    def state(self, state):
        if isinstance(state, str):  # not a date type     
            state = state=datetime.today()
        self.state = state
    
    # age is calculated field, age is returned according to date of birth
    @property
    def age(self):
        today = datetime.today()
        return today.year - self.state.year - ((today.month, today.day) < (self.state.month, self.state.day))
    
    # 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 {
            "customerid": self.id,
            "customername": self.name,
            "customeruid": self.uid,
            "state": self.state,
            "age": self.age,
        }

    # CRUD update: updates user name, password, phone
    # returns self
    def update(self, customername="", customeruid="", customerpassword=""):
        """only updates values with length"""
        if len(customername) > 0:
            self.customername = customername
        if len(customeruid) > 0:
            self.customeruid = customeruid
        if len(customerpassword) > 0:
            self.set_customerpassword(customerpassword)
        db.session.add(self) # performs update when id exists
        db.session.commit()
        return self

    # CRUD delete: remove self
    # None
    def delete(self):
        db.session.delete(self)
        db.session.commit()
        return None
---------------------------------------------------------------------------
InvalidRequestError                       Traceback (most recent call last)
/vscode/ahadsblog/_notebooks/2023-03-17- 2.4 Hacks.ipynb Cell 4 in <cell line: 17>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-03-17-%202.4%20Hacks.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a> ''' Tutorial: https://www.sqlalchemy.org/library.html#tutorials, try to get into a Python shell and follow along '''
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-03-17-%202.4%20Hacks.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=11'>12</a> # Define the User class to manage actions in the 'users' table
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-03-17-%202.4%20Hacks.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=12'>13</a> # -- Object Relational Mapping (ORM) is the key concept of SQLAlchemy
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-03-17-%202.4%20Hacks.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=13'>14</a> # -- a.) db.Model is like an inner layer of the onion in ORM
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-03-17-%202.4%20Hacks.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=14'>15</a> # -- b.) User represents data we want to store, something that is built on db.Model
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-03-17-%202.4%20Hacks.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=15'>16</a> # -- c.) SQLAlchemy ORM is layer on top of SQLAlchemy Core, then SQLAlchemy engine, SQL
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-03-17-%202.4%20Hacks.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=16'>17</a> class customer(db.Model):
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-03-17-%202.4%20Hacks.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=17'>18</a>     __tablename__ = 'customers'  # table name is plural, class name is singular
     <a href='vscode-notebook-cell://wsl%2Bubuntu/vscode/ahadsblog/_notebooks/2023-03-17-%202.4%20Hacks.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=19'>20</a>     # Define the User schema with "vars" from object

File ~/anaconda3/lib/python3.9/site-packages/flask_sqlalchemy/model.py:100, in BindMetaMixin.__init__(cls, name, bases, d, **kwargs)
     97     if metadata is not parent_metadata:
     98         cls.metadata = metadata
--> 100 super().__init__(name, bases, d, **kwargs)

File ~/anaconda3/lib/python3.9/site-packages/flask_sqlalchemy/model.py:120, in NameMetaMixin.__init__(cls, name, bases, d, **kwargs)
    117 if should_set_tablename(cls):
    118     cls.__tablename__ = camel_to_snake_case(cls.__name__)
--> 120 super().__init__(name, bases, d, **kwargs)
    122 # __table_cls__ has run. If no table was created, use the parent table.
    123 if (
    124     "__tablename__" not in cls.__dict__
    125     and "__table__" in cls.__dict__
    126     and cls.__dict__["__table__"] is None
    127 ):

File ~/anaconda3/lib/python3.9/site-packages/sqlalchemy/orm/decl_api.py:199, in DeclarativeMeta.__init__(cls, classname, bases, dict_, **kw)
    196         cls._sa_registry = reg
    198 if not cls.__dict__.get("__abstract__", False):
--> 199     _as_declarative(reg, cls, dict_)
    200 type.__init__(cls, classname, bases, dict_)

File ~/anaconda3/lib/python3.9/site-packages/sqlalchemy/orm/decl_base.py:248, in _as_declarative(registry, cls, dict_)
    242 def _as_declarative(
    243     registry: _RegistryType, cls: Type[Any], dict_: _ClassDict
    244 ) -> Optional[_MapperConfig]:
    245 
    246     # declarative scans the class for attributes.  no table or mapper
    247     # args passed separately.
--> 248     return _MapperConfig.setup_mapping(registry, cls, dict_, None, {})

File ~/anaconda3/lib/python3.9/site-packages/sqlalchemy/orm/decl_base.py:329, in _MapperConfig.setup_mapping(cls, registry, cls_, dict_, table, mapper_kw)
    325     return _DeferredMapperConfig(
    326         registry, cls_, dict_, table, mapper_kw
    327     )
    328 else:
--> 329     return _ClassScanMapperConfig(
    330         registry, cls_, dict_, table, mapper_kw
    331     )

File ~/anaconda3/lib/python3.9/site-packages/sqlalchemy/orm/decl_base.py:578, in _ClassScanMapperConfig.__init__(self, registry, cls_, dict_, table, mapper_kw)
    574 self._extract_mappable_attributes()
    576 self._extract_declared_columns()
--> 578 self._setup_table(table)
    580 self._setup_inheriting_columns(mapper_kw)
    582 self._early_mapping(mapper_kw)

File ~/anaconda3/lib/python3.9/site-packages/sqlalchemy/orm/decl_base.py:1663, in _ClassScanMapperConfig._setup_table(self, table)
   1655             table_kw["autoload"] = True
   1657         sorted_columns = sorted(
   1658             declared_columns,
   1659             key=lambda c: column_ordering.get(c, 0),
   1660         )
   1661         table = self.set_cls_attribute(
   1662             "__table__",
-> 1663             table_cls(
   1664                 tablename,
   1665                 self._metadata_for_cls(manager),
   1666                 *sorted_columns,
   1667                 *args,
   1668                 **table_kw,
   1669             ),
   1670         )
   1671 else:
   1672     if table is None:

File ~/anaconda3/lib/python3.9/site-packages/flask_sqlalchemy/model.py:147, in NameMetaMixin.__table_cls__(cls, *args, **kwargs)
    144 # Check if a table with this name already exists. Allows reflected tables to be
    145 # applied to models by name.
    146 if key in cls.metadata.tables:
--> 147     return sa.Table(*args, **kwargs)
    149 # If a primary key is found, create a table for joined-table inheritance.
    150 for arg in args:

File <string>:2, in __new__(cls, *args, **kw)

File ~/anaconda3/lib/python3.9/site-packages/sqlalchemy/util/deprecations.py:277, in deprecated_params.<locals>.decorate.<locals>.warned(fn, *args, **kwargs)
    270     if m in kwargs:
    271         _warn_with_version(
    272             messages[m],
    273             versions[m],
    274             version_warnings[m],
    275             stacklevel=3,
    276         )
--> 277 return fn(*args, **kwargs)

File ~/anaconda3/lib/python3.9/site-packages/sqlalchemy/sql/schema.py:428, in Table.__new__(cls, *args, **kw)
    421 @util.deprecated_params(
    422     mustexist=(
    423         "1.4",
   (...)
    426 )
    427 def __new__(cls, *args: Any, **kw: Any) -> Any:
--> 428     return cls._new(*args, **kw)

File ~/anaconda3/lib/python3.9/site-packages/sqlalchemy/sql/schema.py:460, in Table._new(cls, *args, **kw)
    458 if key in metadata.tables:
    459     if not keep_existing and not extend_existing and bool(args):
--> 460         raise exc.InvalidRequestError(
    461             "Table '%s' is already defined for this MetaData "
    462             "instance.  Specify 'extend_existing=True' "
    463             "to redefine "
    464             "options and columns on an "
    465             "existing Table object." % key
    466         )
    467     table = metadata.tables[key]
    468     if extend_existing:

InvalidRequestError: Table 'customers' is already defined for this MetaData instance.  Specify 'extend_existing=True' to redefine options and columns on an existing Table object.