<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Chevy Vall</title>
    <description>The latest articles on DEV Community by Chevy Vall (@gutmaster).</description>
    <link>https://dev.to/gutmaster</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1264302%2Fa4e58456-eef6-48ce-8d6c-78dfd26292fd.png</url>
      <title>DEV Community: Chevy Vall</title>
      <link>https://dev.to/gutmaster</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/gutmaster"/>
    <language>en</language>
    <item>
      <title>Flask me how to Login!</title>
      <dc:creator>Chevy Vall</dc:creator>
      <pubDate>Thu, 20 Mar 2025 21:34:13 +0000</pubDate>
      <link>https://dev.to/gutmaster/flask-me-how-to-login-3e8a</link>
      <guid>https://dev.to/gutmaster/flask-me-how-to-login-3e8a</guid>
      <description>&lt;p&gt;Many applications and websites need a way to keep track of and coordinate session and user information on the back end. While there are a plethora of ways to implement these features, Flask-Login easily provides us with the most important. The examples routes I'll be showing use flask-RESTful to organize the api, and I'll be showing as simple an implementation as I can manage. Let's take a look.&lt;/p&gt;

&lt;p&gt;First, we install:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ pip install flask-login
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we'll import and create our LoginManager class, then initialize it with our app, assuming that we're using a config file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# config.py
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our app.py imports:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app.py
from flask_login import login_user, logout_user, current_user

from config import app, db, api, login_manager
from models import User
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's a lot of imports! Let's break them down: &lt;em&gt;login_user&lt;/em&gt; is a function that takes a user and stores them as the &lt;em&gt;current_user&lt;/em&gt; and adds their id to the session. &lt;em&gt;logout_user&lt;/em&gt; clears the &lt;em&gt;current_user&lt;/em&gt; and cleans up relevant cookies from the session. &lt;/p&gt;

&lt;p&gt;We'll also need provide a &lt;em&gt;user_loader&lt;/em&gt; callback to pull the user from our database based on the id stored in session. We don't have to interact with this function directly after it's implemented.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We also have to provide the corresponding class method in our model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# models.py
from flask_login import UserMixin

class User(db.Model, UserMixin):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, unique=True, nullable=False)
    password = db.Column(db.String, nullable=False)

    @classmethod
    def get(self, id):
        return User.query.get(id)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You may have noticed we're inheriting from &lt;strong&gt;UserMixin&lt;/strong&gt; as well. Flask-login requires your model to have the following properties and methods:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    def is_authenticated(self):
        return True
    def is_active(self):
        return True
    def is_anonymous(self):
        return False
    def get_id(self):
        return str(self.id)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While you can overwrite these, &lt;strong&gt;UserMixin&lt;/strong&gt; allows you to shortcut including these by providing default implementations if you don't need the extra functionality.&lt;/p&gt;

&lt;p&gt;Back in our app.py we can take a look at handling request to log in:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Login(Resource):
    def post(self):
        data = request.json
        user = User.query.filter_by(username=data.get("username")).first()
        if user is None or not user.authenticate(data.get("password")):
            response = make_response({'error':'Invalid username or ID'})
            response.status_code = 401
            return response

        login_user(user)
        return make_response(user.to_dict(), 201)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The call to &lt;em&gt;login_user&lt;/em&gt; is the magic here, this will store the id of the user that was passed to us in session so that we can easily authenticate and reload the user on a page refresh, as well as set the &lt;em&gt;current_user&lt;/em&gt; to the user passed. We'll return a copy of the user so our front-end can log in too.&lt;/p&gt;

&lt;p&gt;Our logout is even simpler:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Logout(Resource):
    def get(self):
        logout_user()
        return make_response('logout successful', 200)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;logout_user&lt;/em&gt; will clear our the current user's id from session and the &lt;em&gt;current_user&lt;/em&gt; object. We'll return a simple message for our front end.&lt;/p&gt;

&lt;p&gt;And that's it! Flask-login includes many more features than these but this should get you off the ground if you just need a basic login management system.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>flask</category>
      <category>programming</category>
      <category>python</category>
    </item>
    <item>
      <title>Validatorian</title>
      <dc:creator>Chevy Vall</dc:creator>
      <pubDate>Thu, 14 Nov 2024 17:35:03 +0000</pubDate>
      <link>https://dev.to/gutmaster/validatorian-58oh</link>
      <guid>https://dev.to/gutmaster/validatorian-58oh</guid>
      <description>&lt;p&gt;Validations are a method of ensuring that our databases only receive the type of information that is appropriate for each attribute. After all, we wouldn't want a surprise type of data to find it's way into our code and cause unexpected behavior. Fortunately, SQLAlchemy has a package that makes validations quick and easy! &lt;/p&gt;

&lt;p&gt;Let's look at some simple examples. Imagine we have a simple model, Sandwich. Here we have already initialized our database and are importing it from a configuration file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from config import db

class Sandwich(db.Model):
    __tablename__ = 'sandwiches'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    description = db.Column(db.String)
    price = db.Column(db.Float)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we want to add validations to any of these attributes, we'll need to import the validations package first.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;from sqlalchemy.orm import validates&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And then, write our function with the '@validates' decorator inside the model.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @validates('name')
    def validate_name(self, key, value):
        if not value:
            raise ValueError('Name cannot be empty.')
        if type(value) != str:
            raise ValueError('Name must be a string.')
        return value
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So what's going on here? Let's break it down. The @validates is a decorator that lets our ORM know to pass any values received with the key of 'name' through our validation function before adding them to the database. The value we return is what is finally given to our database. The "key" argument is the key that is being evaluated, in this case 'name', the value is the value of that key, so the actual name(hopefully in text) that we are trying to add. So here we are checking to make sure that the name attribute passed in is not empty, and that is in in fact a string. If not, we raise an error.&lt;/p&gt;

&lt;p&gt;We can also run multiple attributes through the same decorator by adding them to it's arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @validates('name', 'description')
    def validate_text(self, key, value):
        if not value:
            raise ValueError(f'{key} cannot be empty.')
        if type(value) != str:
            raise ValueError(f'{key} must be a string.')
        return value
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function validates our name and description attributes, but we won't usually have the same validations to perform on different attributes. Depending on how different and how many validations we have we can do it a couple of different ways. We can run a separate validator for our other attributes, let's add a length validation for our description and price validations too:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @validates('name')
    def validate_name(self, key, value):
        if not value:
            raise ValueError('Name cannot be empty.')
        if type(value) != str:
            raise ValueError('Name must be a string.')
        return value

    @validates('description')
        def validate_description(self, key, value):
        if not value:
            raise ValueError('Description cannot be empty.')
        if type(value) != str:
            raise ValueError('Description must be a string.')
        if not 10 &amp;lt;= len(value) &amp;lt;= 200:
                raise ValueError('Description must be between 10 and 200 characters.')
        return value

    @validates('price')
    def validate_price(self, key, value):
        if type(value) != float:
            raise ValueError('Price must be a float.')
        if not 1 &amp;lt;= value &amp;lt;= 15:
            raise ValueError('Price must be between 1 and 15')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or, we can keep the same validator for both and use the key argument passed in to adjust which validations are run for each attribute.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @validates('name', 'description', 'price')
    def validate(self, key, value):
        if key != 'price:
            if not value:
                raise ValueError(f'{key} cannot be empty.')
            if type(value) != str:
                raise ValueError(f'{key} must be string.')
            if key == 'description':
                if not 10 &amp;lt;= len(value) &amp;lt;= 200:
                    raise ValueError('Description must be between 10 and 200 characters.')
        else:
            if type(value) != float:
                raise ValueError(f'{key} must be a float.')
            if not 1 &amp;lt;= value &amp;lt;= 15:
                raise ValueError('Price must be between 1 and 15')
        return value
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hmm, this is a little messy, let's refactor into 2 separate validators.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @validates('name', 'description')
    def validate_text(self, key, value):
       if not value:
            raise ValueError(f'{key} cannot be empty.')
        if type(value) != str:
            raise ValueError(f'{key} must be string.')
        if key == 'description':
            if not 10 &amp;lt;= len(value) &amp;lt;= 200:
                raise ValueError('Description must be between 10 and 200 characters.')

    @validates('price')
    def validate_price(self, key, value):
        if type(value) != float:
            raise ValueError('Price must be a float.')
        if not 1 &amp;lt;= value &amp;lt;= 15:
            raise ValueError('Price must be between 1 and 15')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's better! Here's our completed model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from sqlalchemy.orm import validates
from config import db

class Sandwich(db.Model):
    __tablename__ = 'sandwiches'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    description = db.Column(db.String)
    price = db.Column(db.Float)

    @validates('name', 'description')
    def validate_text(self, key, value):
        if not value:
            raise ValueError(f'{key} cannot be empty.')
        if type(value) != str:
            raise ValueError(f'{key} must be string.')
        if key == 'description':
            if not 10 &amp;lt;= len(value) &amp;lt;= 200:
                raise ValueError('Description must be between 10 and 200 characters.')

    @validates('price')
    def validate_price(self, key, value):
        if type(value) != float:
            raise ValueError('Price must be a float.')
        if not 1 &amp;lt;= value &amp;lt;= 15:
            raise ValueError('Price must be between 1 and 15')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it! Validations are one easy tool to make sure your databases stay right and proper.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>sql</category>
      <category>python</category>
      <category>flask</category>
    </item>
    <item>
      <title>Build an ORM workshop.</title>
      <dc:creator>Chevy Vall</dc:creator>
      <pubDate>Wed, 10 Jul 2024 03:38:12 +0000</pubDate>
      <link>https://dev.to/gutmaster/python-x-sql-1id5</link>
      <guid>https://dev.to/gutmaster/python-x-sql-1id5</guid>
      <description>&lt;p&gt;SQL is the most common programming language used for managing databases, and is used in many large companies for it's robustness and simplicity. But what if we want to integrate it into a larger and more versatile program? This is where an Object Relational Manager comes in! In this post I will talk about and show some examples of the basics of communicating with an SQL database using sqlite3. Most of this will be done through a standardized ORM like SQAlchemy in a professional setting, but it's good to understand what's going on under the hood.&lt;/p&gt;

&lt;p&gt;Before we start talking to our database we'll need to import sqlite3 into our python file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import sqlite3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After importing it, we set up our connection to our database and the cursor through which we'll interact with it. Not that if the file you are trying to connect to doesn't exist, this line will create it before connecting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CONN = sqlite3.connect('pets.db')
CURSOR = CONN.cursor()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In order to track our database information in python, we'll create a class that corresponds to the information contained in a database table. For our example we'll create a database of pets for the user to track.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Pet:
    all = {}

    def __init__(self, name, species, id=None):
        self.id = id
        self.name = name
        self.species = species
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, id, name, and species are columns in our table, and each instance of the class would be a row. We will use the dictionary class attribute all to store individual instances of rows from our database so that we don't have to pull them from the database every time we reference them. We'll leave ID as None on initialization, as it will be assigned after we create our actual database entry for the object.&lt;/p&gt;

&lt;p&gt;Now that our framework is starting to come together, let's look at some examples of running SQL code through our class to build and manipulate our database. Before we do anything, we need to create a table. The syntax is near identical to SQL itself, but is passed as a special string to our CURSOR to run on our database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @classmethod
    def create_table(cls):
        sql = """
            CREATE TABLE IF NOT EXISTS pets (
            id INTEGER PRIMARY KEY,
            name TEXT,
            species TEXT)
        """
        CURSOR.execute(sql)
        CONN.commit()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we'll need to be able to add information into our database. After all, what's a database table without information to organize? We'll do this with a class method 'create' to create an instance, and an instance method 'save' to save itself into the database and the class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @classmethod
    def create(cls, name, species):
        pet = cls(name, species)
        pet.save()
        return pet

    def save(self):
        sql = """
            INSERT INTO pets (name, species)
            VALUES (?, ?)
        """

        CURSOR.execute(sql, (self.name, self.species))
        CONN.commit()

        self.id = CURSOR.lastrowid
        type(self).all[self.id] = self
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that we wrote in '?' symbols instead of the actual values we want to use in our SQL code. The CURSOR.execute function can recognize these and will replace them in order with the values that we pass to it. In this case, self.name and self.species. Then we grab the id of the newly inserted row from the database, and use that as the key for our python dictionary of our instances.&lt;/p&gt;

&lt;p&gt;Now that we have the basics of creating information for our database we can write a short test script to demonstrate.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from pet import Pet

def seed_database():
    Pet.create_table()
    fido = Pet.create("Fido", "Dog")
    print(fido)

seed_database()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What will this print to the console?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;pet.Pet object at 0x7f8fc4940cd0&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are creating an object at least, let's update Pet class to override the basic print functionality, we can do this with the special function '&lt;strong&gt;repr&lt;/strong&gt;'.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    def __repr__(self):
        return f"&amp;lt;Pet {self.id}: {self.name}, {self.species}&amp;gt;"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function take the instance of the class and returns a formatted string to easily display our information.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Pet 1: Fido, Dog&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This shows that it's working, but it's nothing you couldn't do with just Python objects. The obvious advantage of a database is that it's saved to a separate file so your data persists between executions of your program. Let's separate this into a simple script to seed the database, and one to print it out to demonstrate. And while we're at it, we'll add a few more functions to our Pet class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import sqlite3

CONN = sqlite3.connect('database.db')
CURSOR = CONN.cursor()

class Pet:
    # Dictionary of objects saved to the database.
    all = {}

    def __init__(self, name, species, id=None):
        self.id = id
        self.name = name
        self.species = species

    def __repr__(self):
        return f"&amp;lt;Pet {self.id}: {self.name}, {self.species}&amp;gt;"

    @classmethod
    def create_table(cls):
        """ Create a new table to persist the attributes of Animal instances """
        sql = """
            CREATE TABLE IF NOT EXISTS pets (
            id INTEGER PRIMARY KEY,
            name TEXT,
            species TEXT)
        """
        CURSOR.execute(sql)
        CONN.commit()

    @classmethod
    def drop_table(cls):
        sql = """
            DROP TABLE IF EXISTS pets;
        """
        CURSOR.execute(sql)
        CONN.commit()

    @classmethod
    def create(cls, name, species):
        """ Initialize a new Pet instance and save the object to the database """
        pet = cls(name, species)
        pet.save()
        return pet

    def save(self):
        sql = """
            INSERT INTO pets (name, species)
            VALUES (?, ?)
        """

        CURSOR.execute(sql, (self.name, self.species))
        CONN.commit()

        self.id = CURSOR.lastrowid
        type(self).all[self.id] = self

    def update(self):
        sql = """
            UPDATE pets
            SET name = ?, location = ?
            WHERE id = ?
        """
        CURSOR.execute(sql, (self.name, self.location, self.id))
        CONN.commit()

    def delete(self):
        sql = """
            DELETE FROM pets
            WHERE id = ?
        """

        CURSOR.execute(sql, (self.id,))
        CONN.commit()

        # Delete the dictionary entry using id as the key
        del type(self).all[self.id]

        # Set the id to None
        self.id = None

    @classmethod
    def get_all(cls):
        sql = """
            SELECT *
            FROM pets
        """

        rows = CURSOR.execute(sql).fetchall()

        return [cls.instance_from_db(row) for row in rows]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our seed script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from pet import Pet

def seed_database():
    Pet.drop_table()
    Pet.create_table()

    fido = Pet.create("Fido", "Dog")
    lucy = Pet.create("Lucy", "Turtle")
    borris = Pet.create("Borris", "Goldfish")

seed_database()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And our final test script that adds one more entry to the database and displays it's contents.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from pet import Pet

def add_and_display():
    Pet.create("Bob", "Chicken")

    for pet in Pet.get_all(): 
        print(pet)

add_and_display()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if we want to reset our database and give it some initial values, we simply run:&lt;br&gt;
&lt;br&gt;
 &lt;code&gt;$ python lib/seed.py&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;We can see that it persists by running:&lt;br&gt;
&lt;br&gt;
 &lt;code&gt;$ python lib/display.py&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Pet 1: Fido, Dog&amp;gt;
&amp;lt;Pet 2: Lucy, Turtle&amp;gt;
&amp;lt;Pet 3: Borris, Goldfish&amp;gt;
&amp;lt;Pet 4: Bob, Chicken&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each time we run our display script it will add another Bob to the table!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Pet 1: Fido, Dog&amp;gt;
&amp;lt;Pet 2: Lucy, Turtle&amp;gt;
&amp;lt;Pet 3: Borris, Goldfish&amp;gt;
&amp;lt;Pet 4: Bob, Chicken&amp;gt;
&amp;lt;Pet 5: Bob, Chicken&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is far from everything that goes into a good ORM, but it's a good framework to understand what's going on under the hood of a standardized Object Relational Manager.&lt;/p&gt;

</description>
      <category>python</category>
      <category>sql</category>
      <category>programming</category>
      <category>database</category>
    </item>
    <item>
      <title>Routing, Client Side</title>
      <dc:creator>Chevy Vall</dc:creator>
      <pubDate>Thu, 18 Apr 2024 01:56:27 +0000</pubDate>
      <link>https://dev.to/gutmaster/routing-client-side-5ben</link>
      <guid>https://dev.to/gutmaster/routing-client-side-5ben</guid>
      <description>&lt;p&gt;Client side routing is a programming method that lets us use custom urls and a browser's history functions to navigate through a single page application. To accomplish this I've learned to use React Router, which gives us the ability to route different url extensions to separate components in our app, and display them only when the user is on that "page".&lt;/p&gt;

&lt;p&gt;Remember to install react-router-dom first!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;npm install react-router-dom
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After successfully installing react-router-dom into our repository, we must import it into our app, then import the functions that we need from it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import ReactDOM from 'react-dom/client'
import { createBrowserRouter, RouterProvider } from "react-router-dom"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we create our router object using the imported function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const router = createBrowserRouter([
  {
    path: "/",
    element: &amp;lt;Home/&amp;gt;
  }
]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We then create a ReactDOM root and assign the application's root to it. We then have this root render our application through the imported RouterProvider component, passing our router object as a prop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  &amp;lt;RouterProvider router={router} /&amp;gt;);
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After setting all of this up, our application should be running and we're ready to start routing!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Home './Home';

import { createBrowserRouter, RouterProvider } from "react-router-dom";

const router = createBrowserRouter([
  {
    path: "/",
    element: &amp;lt;Home /&amp;gt;
  }
]);

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  &amp;lt;RouterProvider router={router} /&amp;gt;);
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once that's all set up, the only thing we need to do to add a new route is add the path and corresponding element to our router object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const router = createBrowserRouter([
  {
    path: "/",
    element: &amp;lt;Home /&amp;gt;
  },
  {
    path: "/donate",
    element: &amp;lt;DonationForm /&amp;gt;
  }
]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One could navigate to either /home or /donate now by typing the extensions into their browser, but if we want to make this a little more user friendly we'll have to add links. NavLinks are a special component that will navigate to the given url extension.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function NavBar() {
  return (
    &amp;lt;div className="NavBar"&amp;gt;
        &amp;lt;nav&amp;gt;
          &amp;lt;NavLink
            to="/"
            className="nav-link"
          &amp;gt;
            Home
          &amp;lt;/NavLink&amp;gt;
          &amp;lt;NavLink
            to="/library"
            className="nav-link"
          &amp;gt;
            Library
          &amp;lt;/NavLink&amp;gt;
          &amp;lt;NavLink
            to="/donate"
            className="nav-link"
          &amp;gt;
            Donate
          &amp;lt;/NavLink&amp;gt;
        &amp;lt;/nav&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And while we're at it, we should add outlet context so that we can choose which portions of the app we want to conditionally render. This time, we'll need to use the children variable of our router.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const routes = [
    {
        path: "/",
        element: &amp;lt;App /&amp;gt;,
        errorElement: &amp;lt;ErrorPage /&amp;gt;,
        children: [
            {
                path: "/",
                element: &amp;lt;Home /&amp;gt;,
            }, 
            {
                path: "/library",
                element: &amp;lt;Library /&amp;gt;
            },
            {
                path: "/donate",
                element: &amp;lt;DonationForm /&amp;gt;
            }
        ]
    }
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way, the default path leads to app, and app has children that it can choose to render through outlet context.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    return(
        &amp;lt;&amp;gt;
            &amp;lt;header&amp;gt;
                &amp;lt;Header /&amp;gt;
                &amp;lt;NavBar /&amp;gt;
            &amp;lt;/header&amp;gt;
            &amp;lt;Outlet context={data}/&amp;gt;
        &amp;lt;/&amp;gt;
    );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the Header and NavBar components will always render, the Outlet is whatever child we are currently routed to. Data is whatever information we want to pass to the child component.&lt;br&gt;
If we'd like to use the data we pass through context, we need to import and use the function useOutletContext().&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useOutletContext } from "react-router-dom";

function DonationForm(){
    const data = useOutletContext()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also pass objects this way using destructuring.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Outlet context={{books: books, setBooks: setBooks}}/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const {books, setBooks} = useOutletContext()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Routing is neat!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>programming</category>
    </item>
    <item>
      <title>For...what?</title>
      <dc:creator>Chevy Vall</dc:creator>
      <pubDate>Fri, 26 Jan 2024 02:48:12 +0000</pubDate>
      <link>https://dev.to/gutmaster/forwhat-dah</link>
      <guid>https://dev.to/gutmaster/forwhat-dah</guid>
      <description>&lt;p&gt;JavaScript offers a variety of options for looping through objects and arrays. For my own sake I'm going to go over JavaSript's most commonly utilized built in functions for this behavior.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;for in&lt;/strong&gt; statement in JS will pull each &lt;em&gt;key&lt;/em&gt; from the array in turn and assign it to the provided variable(i in this case).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1, 2, 5]
const object = {'big':'dawg', 'manners':0, 'hamburgers':[1,3,0,1]}

for(i in array){
    console.log(i)
}
for(i in object){
    console.log(i)
}

//Output: 
0
1
2
big
manners
hamburgers
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you'd like to access the corresponding element of the array or object this way, you may do so with the bracket [] operator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for(i in array){
    console.log(array[i])
}
for(i in object){
    console.log(object[i])
}

//Output: 
1
2
5
dawg
0
[ 1, 3, 0, 1 ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that if the order that you are walking through your object/array matters it is best not to use &lt;strong&gt;for in&lt;/strong&gt; as the order isn't consistent between implementations.&lt;/p&gt;

&lt;p&gt;If you need to access the element from the array directly you may do so with the &lt;strong&gt;for of&lt;/strong&gt; operator. You may do this with arrays, but JavaScript will throw a TypeError if you try to iterate over an object with &lt;strong&gt;for of&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1, 2, 5]

for(i of array){
    console.log(i)
}

//Output:
1
2
5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Of course you can always you the classic &lt;strong&gt;for&lt;/strong&gt; operator as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1, 2, 5]

for(let i = 0; i &amp;lt; array.length; i++){
    console.log(array[i])
}

//Output:
1
2
5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the classic &lt;strong&gt;for&lt;/strong&gt; operator you declare or reuse a variable to work as your index while iterating, then define at what point you will stop(i &amp;lt; array.length), then put in an operator to apply to the index(i++).&lt;/p&gt;

&lt;p&gt;The last operator I'm going to discuss is the &lt;strong&gt;forEach&lt;/strong&gt; operator. &lt;strong&gt;for each&lt;/strong&gt; is called on an array and takes a callback function as it's only argument. The function automatically takes the value of the currently indexed element in the loop, the index itself, and the entire object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = ['big', 'dawg', [1,3,0,1]]

array.forEach(function(element, index, arr){
    console.log(index, element)
})

//Output:
0 big
1 dawg
2 [ 1, 3, 0, 1 ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you'd like to iterate through an object using &lt;strong&gt;forEach&lt;/strong&gt;, you may can do so by iterating through either the keys, values, or entries of the object by using Object.keys(), Object.values(), or Object.entries() to pull the respective information.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const object = {'size':'big', 'type':'dawg', 'pin':[1,3,0,1]}

console.log("KEYS")
Object.keys(object).forEach(function(key){
    console.log(key)
})
console.log("VALUES")
Object.values(object).forEach(function(value){
    console.log(value)
})
console.log("ENTRIES")
Object.entries(object).forEach(function(entry){
    console.log(entry)
})

//Output:
KEYS
size
type
pin
VALUES
big
dawg
&amp;gt; (4) [1, 3, 0, 1]
ENTRIES
&amp;gt; ['size', 'big']
&amp;gt; ['type', 'dawg']
&amp;gt; ['pin', Array(4)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To recap: &lt;strong&gt;for in&lt;/strong&gt;, classic &lt;strong&gt;for&lt;/strong&gt; to iterate by index, &lt;strong&gt;for of&lt;/strong&gt; and &lt;strong&gt;forEach&lt;/strong&gt; to iterate by element directly. &lt;strong&gt;for in&lt;/strong&gt; is usually best for objects as &lt;strong&gt;forEach&lt;/strong&gt; and &lt;strong&gt;for of&lt;/strong&gt; cannot be invoked on them. Oftentimes the choice comes down to syntax preference but one is usually preferable.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>tutorial</category>
      <category>learning</category>
    </item>
  </channel>
</rss>
