NOTE

As you follow along, make sure to fill in the blanks and complete the coding exercises!

Introduction

When building an application that requires users to create accounts or sign in, handling data related to users is crucial. This data can include things like user profiles, preferences, and activity logs, which can be used to personalize the user experience and improve the application's performance.

For example, by storing a user's name and profile picture, the application can address the user by name and display their picture, creating a more personal experience. Activity logs can also be used to track user behavior and help the application recommend new features or improvements.

By learning how to handle data related to users effectively and responsibly, you'll be equipped with the skills and knowledge needed to build robust and user-friendly applications that meet the needs of your users.

For simplicity purposes, we will be lecturing on how one can store and manipulate user data for future utilization.

Here we go!

Establishing Class/User Data and making a new user

In Python, classes are templates used to create objects, which are instances of those classes. Classes define the data elements (attributes) and methods that describe the behavior of the objects. Let's explore how to define a class and create objects in Python.

Example: Defining a User class

class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email

    def display_info(self):
        print(f"Username: {self.username}, Email: {self.email}")

In this example, we define a User class with a constructor method init that takes username and email as arguments. The display_info method is used to print the user information.

In the context of backend functionality, this class can be used to create, manipulate, and manage user data. For example, when a new user signs up for an account, you could create a new User object with their username and email. This object can then be used to perform various operations, such as validating the user's input, storing the user's data in a database, or processing user-related requests.

Creating a new user:

new_user = User("john_doe", "john@example.com")
new_user.display_info()
Username: john_doe, Email: john@example.com

Lecture Topics:

Establishing Class/User Data and making a new user

In Python, classes are templates used to create objects, which are instances of those classes. Classes define the data elements (attributes) and methods that describe the behavior of the objects. Let's explore how to define a class and create objects in Python.

Example: Defining a User class

class User: def init(self, username, email): self.username = username self.email = email

def display_info(self):
    print(f"Username: {self.username}, Email: {self.email}")

In this example, we define a User class with a constructor method init that takes username and email as arguments. The display_info method is used to print the user information.

Creating a new user:

python

new_user = User("john_doe", "john@example.com") new_user.display_info()

Here, we create a new User object, new_user, with a specified username and email. We then call the display_info method to display the user's information.

Using property decorators (getter and setter)

Property decorators allow developers to access and modify instance data more concisely. The @property decorator creates a getter method, while the @attribute.setter decorator creates a setter method.

Example:

class Employee:
    def __init__(self, employee_id, name):
        self._employee_id = employee_id
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, new_name):
        self._name = new_name

In this example, the Employee class has a name attribute, which is accessed and modified through the name property getter and setter methods. The _name attribute uses an underscore prefix, which is a convention to indicate it should not be accessed directly.

In the context of backend functionality, this Employee class can be used to model employees within an application. You can create instances of this class to store and manage employee data, and the getter and setter methods can be used to access and modify employee information in a controlled way.

Usage:

employee = Employee(1001, "John Doe")
print(employee.name)  # Get the name using the getter method

employee.name = "Jane Doe"  # Set the name using the setter method
print(employee.name)
John Doe
Jane Doe

employee = Employee(1001, "John Doe") print(employee.name) # Get the name using the getter method

employee.name = "Jane Doe" # Set the name using the setter method print(employee.name)

In the context of backend functionality, the getter and setter methods provide a clean and controlled way to access and modify the attributes of an object. This can be particularly useful when interacting with databases, APIs, or other parts of a web application that require the management and manipulation of object attributes.

CHECK: Explain the function of getters and setters in your own words. A getter is used to access a variable within a class, while a setter is used to change its value

class Car:
    def __init__(self, make, model, year):
        self._make = make
        self._model = model
        self._year = year

    @property
    def make(self):
        return self._make

    @make.setter
    def make(self, new_make):
        self._make = new_make

    @property
    def model(self):
        return self._model

    @model.setter
    def model(self, new_model):
        self._model = new_model

    @property
    def year(self):
        return self._year

    @year.setter
    def year(self, new_year):
        self._year = new_year

Take notes here on property decorators and the purpose they serve: In Python programming, decorators are used to modify the behavior of a function or class without changing its source code. They are implemented using the "@" symbol and can be used to add new functionality, such as logging or caching. Decorators are higher-order functions and can be applied in multiple layers. They can also be implemented as classes with the call() method.

Students can then practice creating instances of their Car class and using the getter and setter methods to access and modify the car attributes.

In the context of backend functionality, this Car class can be used to model cars within an application. You can create instances of this class to store and manage car data, and the getter and setter methods can be used to access and modify car information in a controlled way.

Overview

WE COVERED: In conclusion, we have covered essential concepts in object-oriented programming using Python, including:

Defining classes and creating objects
Property decorators (getter and setter)
Class methods and static methods
Inheritance and method overriding
Working with multiple objects and class attributes

These concepts provide a solid foundation for understanding how to model real-world entities using classes and objects in Python. By learning to work with classes, objects, and their methods, students can develop more efficient and modular code.

As students become more comfortable with these concepts, they can explore more advanced topics, such as multiple inheritance, abstract classes, encapsulation, and polymorphism. Additionally, they can apply these principles to practical projects like web development with Flask and SQLite, as discussed earlier.

Overall, mastering object-oriented programming will greatly enhance students' ability to develop complex and maintainable software systems.

Databases and SQlite

SQLite is a software library that provides a relational database management system. Unlike other databases, such as MySQL or PostgreSQL, SQLite is embedded within an application, which means it does not require a separate server process to operate. This makes SQLite a great choice for small-scale applications or for use in situations where you don't want to set up a full database server.

In this lesson, we will be demonstrating how to set up a SQLite database in Flask, which provides an easy-to-use interface for interacting with SQLite databases, and we'll walk through the process of setting up a new database, creating tables, and adding data. We'll also cover some basic SQL commands that you can use to interact with your database, including CREATE TABLE, INSERT, SELECT, UPDATE, and DELETE. By the end of this lesson, you'll have a good understanding of how to work with SQLite databases in Flask and be ready to start building your own applications.

Setting up a SQLite database in Flask

One of the key features of Flask is its ability to work seamlessly with databases, including SQLite. A database is a collection of data stored in an organized manner that can be easily accessed, managed, and updated.

SQlite databse in Flask

from flask import Flask
import sqlite3

# Create a Flask application
app = Flask(__name__)

# Connect to the SQLite database using SQLite3
conn = sqlite3.connect('example.db')

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

# Create a table in the database using SQL commands
cursor.execute('''CREATE TABLE example_table
                 (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

# Commit the changes to the database
conn.commit()

# Close the connection
conn.close()

Basic SQL commands (create, read, update, delete)

SQL is really useful because it helps people do a bunch of things with the data stored in databases. For example, they can use it to create new tables to organize data, add new data to a table, update data that's already there, or delete data that's no longer needed.

CRUD is an acronym that stands for the fundamental operations that can be performed on a database, which are Create, Read, Update, and Delete. A widely-used lightweight database management system is SQLite, which can be easily integrated with different programming languages.

  • C: To create a new record in a database, you must first define the table structure that will store the data. This can be accomplished using SQL commands such as CREATE. Once the table is created, data can be added to it using the INSERT INTO command.

  • R: To retrieve data from the database, you can use the READ command. You can specify which fields you want to retrieve and the conditions you want to apply using the WHERE clause. There are also several functions available to aggregate and manipulate data.

  • U: To modify existing data in the database, you can use the UPDATE command. You will need to specify which table and fields you want to update, and the conditions you want to apply using the WHERE clause.

  • D: To remove data from the database, you can use the DELETE command

Take notes here on the basic components of SQL:

import sqlite3

def menu():
    operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete")
    if operation.lower() == 'c':
        create()
    elif operation.lower() == 'r':
        read()
    elif operation.lower() == 'u':
        update()
    elif operation.lower() == 'd':
        delete()
    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")
Perform Jupyter 'Run All' prior to starting menu

This block of code is a menu function that helps with create, read, update, and delete (CRUD) tasks and displays the schema. The menu function acts as a control point that directs the program to call different functions based on what the user wants to do. When users enter their preferred action, the input is checked to see which function to use. The menu function is created with no arguments and is called repeatedly, displaying the menu options until the user decides to leave.

Creating a Database

import sqlite3

def create_database():
    # Connect to the database (will create it if it doesn't exist)
    connection = sqlite3.connect('instance/professors.db')
    cursor = connection.cursor()

    # Create the professors table if it doesn't already exist
    cursor.execute('''CREATE TABLE IF NOT EXISTS professors (
                    name TEXT,
                    field TEXT,
                    rating REAL,
                    reviews TEXT
                )''')

    # Commit changes and close the connection
    connection.commit()
    connection.close()

# Call the function to create the database
create_database()

Create Function:

import sqlite3

def create():
   database = 'instance/professors.db'
   name = input("Enter the professor's name: ")
   field = input("Enter the professor's field of expertise: ")
   rating = input("Enter the professor's rating (out of 10): ")
   reviews = input("Enter any reviews or comments about the professor: ")


   # Connect to the database and create a cursor to execute SQL commands
   connection = sqlite3.connect(database)
   cursor = connection.cursor()


   try:
       # Execute SQL to insert record into db
       cursor.execute("INSERT INTO professors (name, field, rating, reviews) VALUES (?, ?, ?, ?)", (name, field, rating, reviews))
       # Commit the changes
       connection.commit()
       print(f"{name} has been added to the list of coding professors.")
              
   except sqlite3.Error as error:
       print("Error while inserting record", error)


   # Close cursor and connection
   cursor.close()
   connection.close()

create()
Mr. Mort has been added to the list of coding professors.

The create function allows users to input information about a coding professor and store it in a SQLite database named 'professors.db'. This script prompts the user for the professor's name, field of expertise, rating out of 10, and any reviews or comments about the professor. It then establishes a connection to the SQLite database and creates a cursor object for executing SQL commands.

Read Function

import sqlite3

def read():
    try:
        # Open a connection to the database and create a cursor
        connection = sqlite3.connect('instance/professors.db')
        cursor = connection.cursor()

        # Fetch all records from the professors table
        cursor.execute("SELECT * FROM professors")
        rows = cursor.fetchall()

        # If there are any records, print them
        if len(rows) > 0:
            print("List of coding professors:")
            for row in rows:
                print(f"Name: {row[0]}\nField of expertise: {row[1]}\nRating: {row[2]}\nReviews: {row[3]}\n")
        else:
            print("There are no coding professors in the list.")

    except sqlite3.Error as error:
        print("Error while connecting to the database:", error)

    finally:
        # Close the cursor and the connection to the database
        cursor.close()
        connection.close()

read()
List of coding professors:
Name: Sean Yeung
Field of expertise: Nuclear Chemistry
Rating: 4.0
Reviews: sheesh

Name: Mr. Mort
Field of expertise: CS
Rating: 10.0
Reviews: i

This code demonstrates how to read data from a SQLite database using Python and the sqlite3 library. The first step is to establish a connection to the database and create a cursor object to execute SQL commands. Then, a SELECT query is executed to fetch all records from the "professors" table. If there are any records, the code iterates through each record and prints out the name, field of expertise, rating, and reviews for each coding professor. If there are no records in the table, a message indicating so is printed.

Update Function

import sqlite3

def update():
    database = 'instance/professors.db'
    connection = sqlite3.connect(database)
    cursor = connection.cursor()
    
    try:
        # Get the professor's name to update
        name = input("Enter the name of the professor to update: ")
        
        # Retrieve the current record from the database
        cursor.execute("SELECT * FROM professors WHERE name=?", (name,))
        record = cursor.fetchone()
        
        # If the professor is found, update the record
        if record:
            print("Enter the new information for the professor:")
            field = input(f"Current field: {record[1]}\nNew field: ")
            rating = input(f"Current rating: {record[2]}\nNew rating: ")
            reviews = input(f"Current reviews: {record[3]}\nNew reviews: ")
            
            # Execute SQL to update the record
            cursor.execute("UPDATE professors SET field=?, rating=?, reviews=? WHERE name=?", (field, rating, reviews, name))
            connection.commit()
            
            print(f"{name}'s record has been updated.")
        
        # If the professor is not found, notify the user
        else:
            print(f"No record found for {name}.")
    
    except sqlite3.Error as error:
        print("Error while updating record", error)
    
    # Close cursor and connection
    cursor.close()
    connection.close()
update ()
Enter the new information for the professor:
Mr. Mort's record has been updated.

This is an implementation of an update function for the professors database using the sqlite3 module in Python. The function first establishes a connection to the database file 'instance/professors.db' and creates a cursor object to execute SQL commands. It prompts the user to enter the name of the professor to update and retrieves the corresponding record from the database using a SELECT statement with a WHERE clause to match the professor's name. If the professor is found in the database, the user is prompted to enter new information for the professor's field of expertise, rating, and reviews. The function then executes an UPDATE statement with the new information to update the record in the database.

Delete Function

import sqlite3


def delete():
    # Connect to the database and create a cursor
    connection = sqlite3.connect('instance/professors.db')
    cursor = connection.cursor()

    # Prompt the user for the name of the professor to delete
    name = input("Enter the name of the professor you want to delete: ")

    # Use a SQL query to find the professor with the given name
    cursor.execute("SELECT * FROM professors WHERE name=?", (name,))
    row = cursor.fetchone()

    # If the professor exists, confirm deletion and delete the record
    if row:
        confirm = input(f"Are you sure you want to delete {name}? (y/n): ")
        if confirm.lower() == 'y':
            cursor.execute("DELETE FROM professors WHERE name=?", (name,))
            connection.commit()
            print(f"{name} has been deleted from the list of coding professors.")
    else:
        print(f"{name} not found in the list of coding professors.")

    # Close the cursor and the connection to the database
    cursor.close()
    connection.close()

delete()
Mr Mort not found in the list of coding professors.

This code is a Python function for deleting a record from a SQLite database. The function prompts the user to input the name of the professor they want to delete. It then uses a SQL query to search for the professor in the database. If the professor is found, the user is prompted to confirm the deletion. If the user confirms, the function executes a SQL command to delete the record from the database. The function also prints a message confirming that the professor has been deleted from the list of coding professors. If the professor is not found in the database, the function prints a message indicating that the professor is not in the list.

Our Project ... in the works

SAM Messaging System

Get started with your own!

import sqlite3

# specify the name of the database file
db_file = "countries.db"

# create a connection to the database
conn = sqlite3.connect(db_file)

# create a cursor object
cursor = conn.cursor()

# create a table for countries
cursor.execute('''CREATE TABLE countries
                (id INTEGER PRIMARY KEY,
                 name TEXT,
                 language TEXT,
                 area INTEGER,
                 population INTEGER)''')

# insert data into the countries table
cursor.execute("INSERT INTO countries VALUES (1, 'USA', 'English', 9833520, 331449281)")
cursor.execute("INSERT INTO countries VALUES (2, 'China', 'Chinese', 9596960, 1444216109)")
cursor.execute("INSERT INTO countries VALUES (3, 'India', 'Hindi', 3287263, 1393409038)")
cursor.execute("INSERT INTO countries VALUES (4, 'Russia', 'Russian', 17125242, 145912025)")
cursor.execute("INSERT INTO countries VALUES (5, 'Brazil', 'Portuguese', 8515767, 213993437)")

# commit the changes and close the connection
conn.commit()
conn.close()

HACKS

  • Make sure to fill in all blanks, take notes when prompted, and at least attempt each of the interactive coding exercises. (0.45)

  • Create your own database and create an algorithm that can insert, update, and delete data ralted to user. Points will be awarded based on effort and success. (0.45)

    • I used my API from my lesson and made changes to be more in line with your lesson. The next two code cells show it.
      • Extra Credit: Connect your backend to a visible frontend!
      • Frontend Link
      • Note: This isn't gonna work because the backend only works locally, but it works on my computer. If you really need me to show it I can show it.
# If you've already run the db.init_app(app) function while in this notebook,
# don't do it again until you've closed it!
""" database dependencies to support sqliteDB examples """
from random import randrange
from datetime import date
import os, base64
import json
import pickle
from __init__ import app, db
from sqlalchemy.exc import IntegrityError
from sqlalchemy import PickleType
from werkzeug.security import generate_password_hash, check_password_hash


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

# Define the Post class to manage actions in 'posts' table,  with a relationship to 'users' table

class Films(db.Model):
    __tablename2__ = 'Films'  # table name is plural, class name is singular

    # Define the User schema with "vars" from object
    _name = db.Column(db.String(255), primary_key=True, nullable=False)
    _year = db.Column(db.Integer, unique=False, nullable=False)
    _epcount = db.Column(db.Integer, unique=False, nullable=False)
    _language = db.Column(db.String(255), unique=False, nullable=False)
    _trailer = db.Column(db.String(255), unique = False, nullable=False)
    _eplist = db.Column(PickleType, unique = False, nullable=False)
    # Defines a relationship between User record and Notes table, one-to-many (one user to many notes)
    #posts = db.relationship("Post2", cascade='all, delete', backref='users', lazy=True)

    # constructor of a User object, initializes the instance variables within object (self)
    def __init__(self, name, year, epcount, language, trailer, eplist):
        self._trailer=trailer
        self._name = name
        self._epcount = epcount
        self._year = year
        self._language = language# variables with self prefix become part of the object, 
        self._eplist = eplist
    # 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
    
    @property
    def year(self):
        return self._year
    
    # a setter function, allows name to be updated after initial object creation
    @year.setter
    def year(self, year):
        self._year = year
       
    @property
    def language(self):
        return self._language
    
    # a setter function, allows name to be updated after initial object creation
    @language.setter
    def language(self, language):
        self._language = language

    @property
    def epcount(self):
        return self._epcount
    
    # a setter function, allows name to be updated after initial object creation
    @epcount.setter
    def epcount(self, epcount):
        self._epcount = epcount
        
    @property
    def trailer(self):
        return self._trailer
    
    # a setter function, allows name to be updated after initial object creation
    @trailer.setter
    def trailer(self, trailer):
        self._trailer = trailer
        
    @property
    def eplist(self):
        return self._eplist
    
    @eplist.setter
    def eplist(self, eplist):
        self._eplist = eplist
    # 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
            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 {
            "name": self.name,
            "year": self.year,
            "language":self.language,
            "epcount": self.epcount,
            "eplist": self.eplist,
            "trailer": self.trailer
        }
    #"posts": [post.read() for post in self.posts]
    # CRUD update: updates user name, password, phone
    # returns self

    def update(self, epwatched, neweplist):
        self._epcount += epwatched
        myeplist = self._eplist.copy() # create a copy of the eplist
        for i in neweplist:
            myeplist.append(i)
        self._eplist = myeplist
        db.session.commit()
        return self

    # CRUD delete: remove self
    # None
    def delete(self):
        db.session.delete(self)
        db.session.commit()
        return {"message":f"deleted {self}"}
"""Database Creation and Testing """


# Builds working data for testing
def initFilms():
    """Create database and tables"""
    db.create_all()
    """Tester data for table"""
    u1 = Films(name='test',year=0,epcount = 1,language="Chinmayan",trailer = "7huivfbhgvbhgbrgb4bvdghb",eplist = ["1","2"])

    films = [u1]

            
from flask import Blueprint, request, jsonify
from flask_restful import Api, Resource # used for REST API building
from datetime import datetime

from model.films import Films

film_api = Blueprint('film_api', __name__,
                   url_prefix='/api/films')

# API docs https://flask-restful.readthedocs.io/en/latest/api.html
api = Api(film_api)

class FilmAPI:    
    class _Create(Resource):
        def post(self):
            ''' Read data for json body '''
            body = request.get_json()
            
            ''' Avoid garbage in, error checking '''
            # validate name
            name = body.get("name")
            if name is None or len(name) < 2:
                return {'message': f'Name is missing, or is less than 2 characters'}, 210
            # checks if year is after 1800
            year = int(body.get("year"))
            if year is None or year < 1800:
                return {'message': f'Year is missing, or is before 1800'}, 210
            # Makes sure episode count is 1 or greater
            epcount = int(body.get("epcount"))
            if epcount is None or epcount < 1:
                return {'message': f'Episode count is missing, or is not a valid count'}, 210
            # Makes sure episode list has at least one element, splits data by commas
            eplist = body.get("eplist").split(',')
            if eplist is None or len(eplist) < 1:
                return {'message': f'Eplist is missing, or is less than 1 element'}, 210
            # Checks that language is a real string
            language = body.get("language")
            if language is None or len(language) < 1:
                return {'message': f'Language is missing, or is less than 1 character'}, 210
            # Error handling for trailer is in frontend
            trailer = body.get("trailer")
            fo = Films(name,year,epcount,language,trailer,eplist)
            # create film in database
            film = fo.create()
            # success returns json of film
            if film:
                return jsonify([film.read()])
            # failure returns error
            return {'message': f'Processed {film}, either a format error or Name {film} is duplicate'}, 210

    class _Read(Resource):
        def get(self):
            films = Films.query.all()    # read/extract all films from database
            json_ready = [film.read() for film in films]  # prepare output in json
            return jsonify(json_ready)  # jsonify creates Flask response object, more specific to APIs than json.dumps
    
    class _Update(Resource):
        def put(self):
            body = request.get_json()
            
            
            name = body.get("name")
            # retrieve the object to be updated using a query


            film = Films.query.get(name)
            if film is None:
                return {'message': f'Name not in list'}, 210
            #Get list and number of new episodes
            watched = body.get("watched")
            episodes = body.get("eps")
            film.update(watched,episodes)

            
            
    class _Delete(Resource):
        def delete(self,name):
            films1 = Films.query.all()
            if name == '-':#delete all if like has the hyphen character
                films1 = Films.query.all()
                json_ready = [film.delete() for film in films1]
                return jsonify(json_ready)
            else:
                newfilm = Films.query.get(name)    # read/extract all films from database
                if newfilm:
                    newfilm.delete()
                    return {'message': f'successfully deleted {name}'}
                else:
                    return {'message': f'Film with name {name} not in list'}# returns if name not existing to delete
            

        
            
    # building RESTapi endpoint
    api.add_resource(_Create, '/create')
    api.add_resource(_Read, '/')
    api.add_resource(_Update, '/update')
    api.add_resource(_Delete, '/delete/<string:name>')