Collections

  • Blog Python API code and use of List and Dictionaries.
  • This is code that initializes our own database to store the reviews.

  • From VSCode using SQLite3 Editor, show your unique collection/table in database, display rows and columns in the table of the SQLite database.
    • This is the data table of stored reviews based on if the creator selected the volunteering service
  • From VSCode model, show your unique code that was created to initialize table and create test data. Uses two normal and 1 admin account as instructed
"""Database Creation and Testing """


# Builds working data for testing
def initUsers():
    with app.app_context():
        """Create database and tables"""
        /cards/_all()
        """Tester data for table"""
        u1 = User(name='Thomas Edison', uid='toby', password='123toby', dob=date(1847, 2, 11))
        u2 = User(name='Nicholas Tesla', uid='niko', password='123niko', dob=date(1856, 7, 10))
        u3 = User(name='Alexander Graham Bell', uid='lex')
        u4 = User(name='Grace Hopper', uid='hop', password='123hop', dob=date(1906, 12, 9))
        u5 = User(name='Abe Lincoln2', uid='abe2', password='123abe', dob=date(1906, 12, 9))
        # Add admin as u5 to make it different than user
        u6 = User(name='Admin', uid='admin', password='123admin', dob=date(1906, 12, 9),role='Admin') 
    
        users = [u1, u2, u3, u4,u5,u6]
        

        # Create a Python array with JSON values
        json_array = [
        #'{"title": "FoodBank", "description": "Food Bank", "address": "123 food bank st", "zipcode":"92126", "day":20,"agegroup":"16"}',
        #'{"title": "AnimalShelter", "description": "Animal Shelter", "address": "123 Animal shelter st", "zipcode":"92127", "day":21,"agegroup":"18"}',
        #'{"title": "CommunityService", "description": "Community Service", "address": "123 community service st", "zipcode":"92128", "day":22,"agegroup":"10"}',
        #'{"title": "BeachCleanup", "description": "Beach Cleanup", "address": "123 beach cleanup st", "zipcode":"92129", "day":23,"agegroup":"6"}',
        '{"title": "San Diego Refugee Tutoring", "description": "Tutor refugee students for 2 hours on Tuesdays and Thursdays from 4pm to 6pm.", "address": "4877 Orange Ave, San Diego, CA 92115","zipcode": "92115","date": "2024-02-27","agegroup": "14"}',
        '{"title": "Youth Court", "description": "Teens take the roles of lawyers and judges and hear cases about fellow students and their infractures.", "address": "220 S Broadway, Escondido, CA 92025","zipcode": "92025","date": "2024-02-27","agegroup": "14"}',
        '{"title": "Balboa Natural History Museum", "description": "Volunteers educate visitors in the museum about animals at small display stands.", "address": "1788 El Prado, San Diego, CA 92101","zipcode": "92101","date": "2024-03-02","agegroup": "16"}',
        '{"title": "Step Up", "description": "Mentoring program for girls", "address": "510 South Hewitt Street #111 Los Angeles, CA 90013","zipcode": "90013","date": "2024-03-02","agegroup": "14"}',
        '{"title": "Children Rising", "description": "Tutoring program for students.", "address": "2633 Telegraph Avenue #412 Oakland, CA 94612","zipcode": "94612","date": "2024-03-10","agegroup": "18"}',
        '{"title": "Seattle Animal Shelter", "description": "Help animals get adopted to loving families.", "address": "2061 15th Ave W, Seattle, WA, 98119","zipcode": "98119","date": "2024-03-10","agegroup": "18"}',
        '{"title": "Gods Love We Deliver", "description": "Help cook and deliver meals to those in need.", "address": "166 Avenue of the Americas New York, NY 10013","zipcode": "10013","date": "2024-03-20","agegroup": "18"}',
        '{"title": "Horse Play Therapy Center", "description": "Advance development and healing for children with special needs", "address": "1925 State Road 207 Saint Augustine, FL 32086","zipcode": "32086","date": "2024-03-14","agegroup": "14"}',
        '{"title": "Community Servings Food Heals", "description": "Help deliver food to families experiencing critical or chronic illness and nutrition insecurity", "address": "179 Amory Street Jamaica Plain, MA 02130","zipcode": "02130","date": "2024-03-09","agegroup": "18"}',
        '{"title": "Emmaus", "description": "Help prevent human trafficking and exploitation.", "address": "954 W. Washington Blvd Chicago, IL 60607 ","zipcode": "60607","date": "2024-03-30","agegroup": "18"}',        
        ]
        events_array = [json.loads(json_str) for json_str in json_array]
        num = 0

        """Builds sample user/note(s) data"""
        for user in users:
            num = num + 1
            try:
                '''add a few 1 to 4 events per user'''
                for events in events_array:
                    title = events["title"]+ str(num)
                    description = events["description"]
                    address = events["address"]
                    zipcode = events["zipcode"]
                    edate = events["date"]
                    agegroup = events["agegroup"]
                    user.events.append(Event(title=title, description=description, address=address, zipcode=zipcode, date=datetime.strptime(edate, '%Y-%m-%d').date(), agegroup=agegroup ))
                '''add user/event data to table'''
                user.create()
            except IntegrityError:
                '''fails with bad or duplicate data'''
                db.session.remove()
                print(f"Records exist, duplicate email, or error: {user.uid}")
  • In VSCode using Debugger, show a list as extracted from database as Python objects.
    • This shows the user data object being extracted in the debugger after a postman request
  • In VSCode use Debugger and list, show two distinct example examples of dictionaries, show Keys/Values using debugger.
    • The data for the user is shown under here where the purple text is the key and the value is next to it
  • When a user is created, it shows the data under the user with the purple text being the key and the value is next to it

Blog Python API code and use of Postman to request and respond with JSON.

  • In VSCode, show Python API code definition for request and response using GET, POST, UPDATE methods. Discuss algorithmic condition used to direct request to appropriate Python method based on request method.
    • The API has many CRUD definitions for GET POST and UPDATE responses for modifiying objects, so resources must define and create endpoints while the user api allows GET POST and PUT responses
# building RESTapi endpoint
    api.add_resource(_CRUD, '/')
    api.add_resource(_Security, '/authenticate')

In VSCode, show algorithmic conditions used to validate data on a POST condition.

            ''' 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'}, 400
            # validate uid
            uid = body.get('uid')
            if uid is None or len(uid) < 2:
                return {'message': f'User ID is missing, or is less than 2 characters'}, 400
  • In Postman, show URL request and Body requirements for GET, POST, and UPDATE methods.
  • In Postman, show the JSON response data for 200 success conditions on GET, POST, and UPDATE methods.

  • In Postman, show the JSON response for error for 404 when providing an unknown user ID to a UPDATE request.
    • This is a 400 error due to the user not being found

Frontend

  • In Chrome inspect, show response of JSON objects from fetch of GET, POST, and UPDATE methods.
    • The POST request sends the body of data for the login to the backend in JSON format
  • Blog JavaScript API fetch code and formatting code to display JSON. image
  • In Chrome inspect, show response of JSON objects from fetch of GET, POST, and UPDATE methods. image In the Chrome browser, show a demo (GET) of obtaining an Array of JSON objects that are formatted into the browsers screen. image
  • In JavaScript code, describe fetch and method that obtained the Array of JSON objects.
  • In JavaScript code, show code that performs iteration and formatting of data into HTML. image
  • In the Chrome browser, show a demo (POST or UPDATE) gathering and sending input and receiving a response that show update. Repeat this demo showing both success and failure. image