Collections

Unique SQLite Data Table

Model Code for Initializing Table + Creating Test Data

class Theme(db.Model):
    __tablename__ = 'theme_data'
    id = db.Column(db.Integer, primary_key=True)
    _name = db.Column(db.String(255), unique=False, nullable=False)
    _uid = db.Column(db.String(255), unique=True, nullable=False)
    _password = db.Column(db.String(255), unique=False, nullable=False)
    _role = db.Column(db.String(255))
    theme = db.Column(db.String(10), default='light')
def initTheme():
    with app.app_context():
        db.create_all()
        u1 = Theme(name='Thomas Edison', uid='toby', password='123toby')
        u2 = Theme(name='Nicholas Tesla', uid='niko', password='123niko')
        u3 = Theme(name='Alexander Graham Bell', uid='lex', password='123bell')
        u4 = Theme(name='Grace Hopper', uid='hop', password='123hop')
        u5 = Theme(name='Admin', uid='root', password='root', role="admin")
        themes = [u1, u2, u3, u4, u5]

Lists & Dictionaries

List Extracted from Database

As seen above in the model “Theme” are associated with the users in the database. Here, we see the same “Theme”s for each user listed in the database.

Dictionaries

Here, we see two dictionaries I have included much more clearly in the API file and demonstrated viewing Keys/Values inside VSCode Debugger.

In VSCode using Debugger, show a list as extracted from database as Python objects. In VSCode use Debugger and list, show two distinct example examples of dictionaries, show Keys/Values using debugger.

APIs & JSON

Python API Code

Algorithmic condition: essentially directs incoming requests to the right Python method based on the HTTP request method used. This is made through Flask-Restful’s Resource class, which basically maps each endpoint to a specific HTTP method handler.

For example, the _Name class handles both GET and PUT requests using its get and put methods, while the _Settings class exclusively handles POST requests with its post method. This ovearall ensures clear and efficient routing of requests within the API.

theme_api = Blueprint('theme_api', __name__, url_prefix='/api/theme')
api = Api(theme_api)

class UserAPI:
    class _Name(Resource):
        def get(self):
            name_data = Theme.query.with_entities(Theme._name).all()
            json_ready = [row[0] for row in name_data]
            print(json_ready)
            return jsonify(json_ready)
        
        def put(self):
            body = request.get_json()
            uid = body.get('uid')
            new_name = body.get('new_name')

            # Check if the user exists
            user = Theme.query.filter_by(_uid=uid).first()
            if not user:
                return {'error': 'User not found'}, 404

            # Update the user's name
            user._name = new_name
            db.session.commit()

            return {'message': 'Username updated successfully'}, 200

    class _Settings(Resource):
        def post(self):
            data = request.json.get('settings')
            uid = data.get('uid')
            username = data.get('name')
            password = data.get('password')
            theme = data.get('theme')

            # Check if the provided user credentials match an existing user in the database
            user = Theme.query.filter_by(_uid=uid).first()
            print(user)
            if user is None or not user.is_password(password) or user.name != username:
                return {'error': 'Invalid user credentials or theme'}, 400
            
            # Check if the theme is 'light' or 'dark'
            if theme not in ['light', 'dark']:
                return {'error': 'Invalid theme specified'}, 400
            
            # Update the user's theme setting
            user.theme = theme
            db.session.commit()

            return {'message': 'Settings saved successfully'}, 200

Conditions to Validate a POST Condition

This condition used to validate data on a POST request in my API involves checking whether the user credentials match an existing user in the database based on uid, password, and username. If any conditions fail (pretty much if user isn’t found) a JSON error response with an appropriate error message and a status code of 400 should be returned.

Postman

PUT Sample Body Data

POST Sample Body Data

200 Success for PUT

200 Success for POST

400 Error

404 Error

Here, I got rid of the “uid” we had earlier for this test. That is obviously an invalid user credentials combination, so it returns an error.

Frontend

Iteration

POST Success (Theme Feature)

Success for Theme Changing occurs upon entering existing credentials and an existing theme (light/dark).

In my code, I believe that the arrays are obtained when I retrieve user input values from HTML forms, organize them into a JavaScript object, and send a POST request to the backend API. After receiving a response, I handle success or error conditions by displaying corresponding messages to the user and logging to the console.

POST Failure

Error occured upon me leaving empty spaces, leading to invalid input and therefore a corresponding example error.

PUT Success (Username Feature)

Here, successful Username Changing can be found occurring upon entering our existing credentials and specifying a new name.

PUT Failure

Error here occurred upon me leaving empty spaces, invalid input according to iteration since the credentials don’t exist in the database, therefore a corresponding example error occurs.

Frontend JavaScript Code

Theme Code Success Handling

When the user clicks the “Save Changes” saveSettings() is called. This constructs an object containing the user’s credentials and selected theme, then sends a POST request to the backend API endpoint. Upon receiving a successful response from the server (HTTP status code 200), the then() method is called, displaying an alert message to the user indicating that the settings have been saved successfully.

Theme Code Error Handling

If the backend API returns an error response (non-200 status code), the catch() method is invoked. In this case, the error message provided by the server is displayed to the user in red text below the form with the ID “error-message”. This message basically tells the user that there was an issue saving the settings (if the user or theme do not exist). The error message is logged to the console, too.

Username Changing Code Success Handling

When user clicks “Change Username”, changeUsername() is executed. This function sends a PUT request to the backend API with updated username data. Upon receiving a successful response from the server, an alert message is displayed, indicating to the user of the success.

Username Changing Code Error Handling

This is obviously pretty similar to error handling for Theme. If the server returns an error response (non-200 status code), the catch() method is triggered. The error message provided by the server is displayed to user in red with ID “username-error-message”. This tells the user that there was an issue changing the username, primarily that the user does not exist.

Additional Algorithm Analysis

“Show algorithms and preparation of data for analysis. This includes cleaning, encoding, and one-hot encoding.”

  • CSV file data cleaned
    • DayPart column cleaned so its values are in 1’s (Morning) and 0’s (Afternoon) - binary usage
    • DayType column cleaned so its values are in 1’s (weekend) and 0’s (weekday) - binary usage
    • Time column cleaned so the only thing being considered is hours from the time format (saved in the CSV)

“Show algorithms and preparation for predictions.”

  • Code cleans the CSV
    • Targets (item to be predicted) as y-value in logistic regression and decision tree and features (item for predict) as x-value in both logistic regression and decision tree

  • Code cleans JSON (input)
    • DayPart column cleaned so its values are in 1s (Morning) and 0s (Afternoon)
    • DayType column cleaned so its values are in 1s (weekend) and 0s (weekday)
    • Time column cleaned so from time format saved in CSV the only thing considered is hours