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

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()

Here's a step-by-step breakdown of how the code relates to backend functionality:

new_user = User("john_doe", "john@example.com"): This line creates a new User object, initializing it with the username "john_doe" and the email "john@example.com". This could represent a user who has just signed up for an account, and the input values would typically come from user input, such as a registration form.

new_user.display_info(): This line calls the display_info method on the new_user object, which prints the user's information (username and email) to the console. In a real-world backend application, you might use this method or a similar one to display user information in logs, send a welcome email, or create an API response with the user's data.

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)

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.

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

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.

The benefits of using SQLite include its simplicity, small footprint, and portability. Because SQLite is embedded in an application, you don't need to worry about setting up a separate database server or dealing with complicated configuration files. SQLite is also very lightweight, with a small memory footprint, making it ideal for use in small-scale applications or situations where resources are limited. In addition, SQLite databases are stored as a single file, which means they can easily be moved between different systems or shared with other users. This makes SQLite a great choice for developers who need to distribute their applications or work on multiple platforms.

In this lesson, we will be demonstrating how to set up a SQLite database in Flask, a popular Python web framework. Flask 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

Flask is a popular Python web framework that enables developers to build web applications easily and quickly. Flask is classified as a micro-framework because it provides only the essential tools and features needed for building web applications. 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. Flask makes it easy to create a web application that interacts with a SQLite database by providing several built-in tools and extensions. Flask's database integration capabilities allow developers to create applications that can perform complex data manipulation and retrieval operations, such as searching, filtering, sorting, and aggregating data. In order to set up a SQLite database in Flask, we need to import the necessary libraries and tools, create a Flask application, connect to the SQLite database using SQLite3, create a cursor object to execute SQL commands, and create tables in the database using SQL commands. Flask provides several extensions and tools for working with SQLite databases, including Flask-SQLAlchemy, Flask-SQLite3, and Flask-Admin. These tools provide a high-level interface for interacting with the database, making it easy to perform common operations such as adding, updating, and deleting records.

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

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")

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.

This menu function is especially helpful for easily and efficiently managing CRUD tasks. To run the script, the menu function is called within a try block, and if there is an error, the except block catches it and shows a message guiding the user to perform a "Run All" operation before starting the menu. This ensures that all necessary code cells have been executed in the Jupyter Notebook environment. This menu function is flexible and can be adjusted for different applications and projects where CRUD operations are necessary, providing a user-friendly interface and efficient error handling.

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()

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. Within a try block, the cursor.execute() method is called with an SQL INSERT command to insert a new record into the 'professors' table, using placeholders to prevent SQL injection attacks. The connection.commit() method saves the changes to the database, and if the record is inserted successfully, a confirmation message is printed. In case of errors, the except block catches the sqlite3.Error exception and prints an error message. Finally, the cursor and the connection to the database are closed, and the create() function is called to execute the code, showcasing a practical way to store user-inputted data in a SQLite database. This create function can be easily adapted to other projects where it is necessary to store user-inputted data.

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()

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. If any error occurs during the execution of the code, an error message is printed to the console. Finally, the cursor and the connection to the database are closed to ensure that resources are freed up and prevent memory leaks.

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 ()

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. If the professor is not found, the function notifies the user that no record was found. Finally, the function closes the cursor and connection to the database. The try-except block is used to catch any potential errors that may occur during the execution of the function.

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()

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.

To accomplish these tasks, the function first establishes a connection to the SQLite database using the sqlite3.connect() method. It then creates a cursor object that is used to execute SQL commands. The function prompts the user to enter the name of the professor they want to delete and then uses a SQL query to search the database for the professor with that name. The cursor object's execute() method is called with the SQL query and a tuple containing the name of the professor as its argument. The fetchone() method is then called on the cursor object to retrieve the record that matches the query. If the professor is found, the function prompts the user to confirm the deletion. If the user confirms, the cursor object's execute() method is called with another SQL query to delete the record from the database. The commit() method is called on the connection object to save the changes to the database. Finally, the function closes the cursor and connection to the database using the close() method on each object.

Our Project ... in the works

SAM Messaging System

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)

    • Extra Credit: Connect your backend to a visible frontend!
""" 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

import sqlite3

# Define a Book class
class Book:
    def __init__(self, title, author, year_published, isbn):
        self.title = title
        self.author = author
        self.year_published = year_published
        self.isbn = isbn

# Create a connection to the database
conn = sqlite3.connect('books.db')

# Create a cursor object
c = conn.cursor()

# Create a table to store books
c.execute('''CREATE TABLE books
             (title text, author text, year_published int, isbn text)''')

# Define some sample books
b1 = Book('To Kill a Mockingbird', 'Harper Lee', 1960, '9780061120084')
b2 = Book('1984', 'George Orwell', 1949, '9780451524935')
b3 = Book('Pride and Prejudice', 'Jane Austen', 1813, '9780486284736')

# Add the sample books to the database
books = [b1, b2, b3]
for book in books:
    c.execute("INSERT INTO books VALUES (?, ?, ?, ?)",
              (book.title, book.author, book.year_published, book.isbn))

# Save changes to the database
conn.commit()

# Close the connection to the database
conn.close()
import sqlite3
db = "/home/b3nto4lunch/vscode/Ederick-s-2022-2023-APCSP-Blog/_notebooks/instance/books.db"

# Define the Book class
class Book:
    def __init__(self, title, author, year_published, isbn):
        self.title = title
        self.author = author
        self.year_published = year_published
        self.isbn = isbn

# Define a function to display all the books in the database
def display_books():
    with sqlite3.connect(db) as conn:
        c = conn.cursor()
        c.execute("SELECT * FROM books")
        books = c.fetchall()
        if books:
            for book in books:
                print(f"{book[0]} - {book[1]} by {book[2]}, published in {book[3]}. ISBN: {book[4]}")
        else:
            print("There are no books in the database.")

# Define a function to add a new book to the database
def add_book():
    title = input("Enter the title of the book: ")
    author = input("Enter the author of the book: ")
    year_published = input("Enter the year the book was published: ")
    isbn = input("Enter the ISBN of the book: ")
    new_book = Book(title, author, year_published, isbn)
    with sqlite3.connect(db) as conn:
        c = conn.cursor()
        c.execute("INSERT INTO books VALUES (?, ?, ?, ?)", (new_book.title, new_book.author, new_book.year_published, new_book.isbn))
        print(f"{new_book.title} by {new_book.author} has been added to the database.")

# Define a function to update an existing book in the database
def update_book():
    isbn = input("Enter the ISBN of the book you want to update: ")
    with sqlite3.connect(db) as conn:
        c = conn.cursor()
        c.execute("SELECT * FROM books WHERE isbn=?", (isbn,))
        book = c.fetchone() # fetchone() Method. This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available.
        if book:
            print(f"You are updating {book[0]} by {book[1]}")
            title = input("Enter the new title of the book (leave blank to keep the same): ")
            author = input("Enter the new author of the book (leave blank to keep the same): ")
            year_published = input("Enter the new year the book was published (leave blank to keep the same): ")
            if title:
                c.execute("UPDATE books SET title=? WHERE isbn=?", (title, isbn))
            if author:
                c.execute("UPDATE books SET author=? WHERE isbn=?", (author, isbn))
            if year_published:
                c.execute("UPDATE books SET year_published=? WHERE isbn=?", (year_published, isbn))
            print(f"{book[0]} by {book[1]} has been updated in the database.")
        else:
            print("No book with that ISBN was found in the database.")

# Define a function to delete an existing book from the database
def delete_book():
    isbn = input("Enter the ISBN of the book you want to delete: ")
    with sqlite3.connect(db) as conn:
        c = conn.cursor()
        c.execute("SELECT * FROM books WHERE isbn=?", (isbn,))
        book = c.fetchone()
        if book:
            confirm = input(f"Are you sure you want to delete {book[0]} by {book[1]}? (y/n)")
            if confirm.lower() == "y":
                c.execute("DELETE FROM books WHERE isbn=?", (isbn,))
                print(f"{book[0]} by {book[1]} has been deleted from the database.")
        else:
            print("No")
add_book()
Example by CRUD has been added to the database.