<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Halim Choi on Medium]]></title>
        <description><![CDATA[Stories by Halim Choi on Medium]]></description>
        <link>https://medium.com/@choihalim?source=rss-4d3fa1a86317------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aeLaBF-3tILOj_WuE8EKBw.jpeg</url>
            <title>Stories by Halim Choi on Medium</title>
            <link>https://medium.com/@choihalim?source=rss-4d3fa1a86317------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:33:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@choihalim/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Procrank: how memory counts]]></title>
            <link>https://medium.com/@choihalim/procrank-how-memory-counts-3b74e43a4d77?source=rss-4d3fa1a86317------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b74e43a4d77</guid>
            <category><![CDATA[adb]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Halim Choi]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 16:29:37 GMT</pubDate>
            <atom:updated>2025-07-14T16:29:37.726Z</atom:updated>
            <content:encoded><![CDATA[<p>In Linux environments, a tool like procrank becomes essential if you’re developing Android apps or troubleshooting performance issues on embedded systems. Understanding how much memory each process consumes is critical to identifying memory leaks and understanding embedded systems.</p><h3>What is Procrank?</h3><p>procrank is a command-line tool used to display memory usage statistics for each process running on an Android device. It reads from the /proc filesystem, which contains runtime system information like memory stats for each process.</p><p>It provides a detailed look at how memory is distributed across processes. This is especially useful on systems with constrained memory, such as smartphones, tablets, and embedded Linux devices.</p><h3>How is Memory Shared?</h3><p>Before we dive into the output of procrank, it’s important to understand that <strong>memory in Android is shared</strong>. For instance, if two apps use the same system library, the library is loaded into memory once but both apps use it. So, the question is: How do we fairly account for memory that’s shared?procrank helps answer by breaking down memory usage into four key metrics:</p><p>Example:</p><ul><li>The app has access to 150MB of memory (VSS).</li><li>It’s actively using 120MB of RAM (RSS).</li><li>Its fair share is 90MB (PSS).</li><li>Only 60MB is unique to it (USS), meaning killing the app would free 60MB.</li></ul><pre>  PID      Vss      Rss      Pss      Uss  cmdline<br>12345  150000K  120000K   90000K   60000K  trojan.memory.exe</pre><h3>VSS — Virtual Set Size</h3><ul><li>The total amount of memory mapped by the process.</li><li>Including all memory the process can access — private, shared, unused, swapped, etc.</li><li><strong>Does not </strong>distinguish between used and reserved memory.</li><li><strong>Think of it as:</strong> The maximum size of the memory box a process might use.</li></ul><h3>RSS — Resident Set Size</h3><ul><li>The amount of physical memory currently held in RAM for the process.</li><li><strong>Includes:</strong> Both private and shared pages.</li><li>Shared memory is counted fully for every process, which<strong> can lead to double-counting</strong>.</li><li><strong>Think of it as:</strong> What’s currently “in hand,” even if some of it is borrowed from others.</li></ul><h3>PSS — Proportional Set Size</h3><ul><li>A fair estimate of the process’s memory usage (best metric for comparing processes).</li><li><strong>Includes:</strong> Private memory + a fair share of shared memory (e.g., if 2 processes share 1 MB, each gets 0.5 MB).</li><li><strong>Think of it as:</strong> The best estimate of how much memory the process is really “responsible” for.</li></ul><h3>USS — Unique Set Size</h3><ul><li>The memory used <em>only</em> by this process.</li><li><strong>Includes:</strong> Only private, unshared memory.</li><li>Shows what memory would be freed if the process were killed.</li><li><strong>Think of it as:</strong> The “owned” portion of the memory.</li></ul><h3>Summary</h3><p><strong>VSS - </strong>General memory map (not super useful alone)</p><p><strong>RSS - </strong>Total RAM in use (be careful for double counting)</p><p><strong>PSS - </strong>Most accurate measure of app memory</p><p><strong>USS - </strong>Best for knowing what’s freed when app is killed</p><p>In general, <strong>proportional size set (PSS)</strong> is the best metric when it comes to measuring and comparing the amount of memory a specific process is responsible for. Estimating the amount of memory certain processes require allows for optimization.</p><p>Memory usage can be tricky, especially when calculated with shared resources. procrank helps developers and system engineers understand memory distribution at a detailed level. Monitoring the proportional size set of individual processes, developers can make smarter decisions about memory optimization, app performance, and system tuning.</p><p>Whether you’re debugging an Android app, building an embedded system, or just curious how memory really works, procrank is a powerful tool to have in your arsenal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b74e43a4d77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Automating Guest Wi-Fi Captive Portals with Selenium (Google Chrome)]]></title>
            <link>https://medium.com/@choihalim/python-automating-guest-wi-fi-captive-portals-with-selenium-google-chrome-9d2788d6e785?source=rss-4d3fa1a86317------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d2788d6e785</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[wifi]]></category>
            <category><![CDATA[macro]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Halim Choi]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 22:06:59 GMT</pubDate>
            <atom:updated>2023-12-20T22:06:59.552Z</atom:updated>
            <content:encoded><![CDATA[<p><em>*This article is intended for educational purposes only. Use responsibly!*</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lfMHwuMa5R73Izj5" /><figcaption>Photo by <a href="https://unsplash.com/@plhnk?utm_source=medium&amp;utm_medium=referral">Paul Hanaoka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem:</h3><p>I am required to use a guest Wi-Fi connection daily at work and find it difficult to manually enter my information every time.</p><h3>Solution:</h3><p>Create a macro that automates the process of filling out personal information, clicking submission buttons, and closing the broswers when finished.</p><p>First, we must import necessary modules such as <strong><em>logging</em></strong>, <strong><em>subprocess</em></strong>, <strong><em>time</em></strong>, <strong><em>traceback</em></strong>, <strong><em>warnings</em></strong>, and <strong><em>webdriver </em></strong>from <strong><em>selenium.</em></strong></p><pre>import logging<br>import subprocess<br>import time<br>import traceback<br>import warnings<br>from selenium import webdriver</pre><p>Below is the code required in order to set up logging. You can replace the filename parameter ‘wifi_login.log’ with whatever you wish the filename to be! Just make sure to have ‘.log’ at the end of the file name.</p><pre># Set up logging<br>warnings.filterwarnings(action=&#39;ignore&#39;)<br>logging.basicConfig(filename=&#39;wifi_login.log&#39;, level=logging.INFO,<br>                    format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*Cdvx2gvpNpHPMr15xdSWBw.png" /><figcaption>* example of logging notepad file *</figcaption></figure><p>Once this is set up, you will be able to configure important logs recorded throughout the automated internet connection process and keep track of what the script is doing at any given time. Here is an example of a log event I have created for whenever disconnection from the current Wi-Fi network is successful:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*73EaQVoEJeIC3JEavFEEvQ.png" /><figcaption>* example of a log *</figcaption></figure><p>Next, we will need to define some essential global variables in order for the script to function and be fully customizable to your guest Wi-Fi captive portal.</p><pre># Define network name (SSID), registration/landing page URLs,<br># and login information<br><br>network_name = &quot;Enter the name of the Wi-Fi network you wish to connect to&quot;<br>target_url = &quot;https://www.ThisIsMyGuestWifiSuccessPageAfterConnecting.com/&quot;<br>website_link = &quot;http://www.ThisIsMyGuestWifiLoginRegistrationPage.com/Form&quot;<br><br># Enter the fields required to login (ex: room #, last name, etc)<br>username = &quot;guest&quot;<br>email = &quot;guest@gmail.com&quot;<br>phone = &quot;2483184938&quot;<br><br># Define actions, &#39;send_keys&#39; enters letters/numbers, &#39;click&#39; submits<br>sks = &quot;send_keys&quot;<br>click = &quot;click&quot;</pre><p>Now we will need to do some inspection on the guest Wi-Fi registration form to find the HTML element IDs for each required field. Here is an example of the element IDs.</p><pre># Define element IDs for form fields<br>element_for_username = &quot;ID_formf9f21400_guest_register_visitor_name&quot;<br>element_for_email = &quot;ID_formf9f21400_guest_register_email&quot;<br>element_for_phone = &quot;ID_formf9f21400_guest_register_visitor_phone_intl&quot;<br>element_for_checkbox = &quot;&quot;<br>element_for_submit_1 = &quot;ID_formf9f21400_guest_register_submit&quot;<br>element_for_submit_2 = &quot;ID_forme2917b01_guest_register_receipt_submit&quot;</pre><p>If you are not familiar with accessing HTML element IDs, classes, etc. please refer to this <a href="https://support.demandbase.com/hc/en-us/articles/360058035472-Find-an-HTML-ID-or-Name#:~:text=Steps-,Context,or%20name%20of%20an%20element.">source</a> in order to find your necessary IDs.</p><p>This next step is optional, in case you might need to use this script on computers that do not have Python or its modules installed already. (The function calls ‘pip install’ on the modules we have already imported in the beginning)</p><pre># install required packages<br>def pip_install(module):<br>    try:<br><br>        print(module + &#39; module install&#39;)<br>        subprocess.run([&#39;pip&#39;, &#39;install&#39;, module], capture_output=True,<br>                       text=True, creationflags=subprocess.CREATE_NO_WINDOW)<br><br>        print(module + &#39; module install complete&#39;)<br>        return True<br>    except:<br>        print(traceback.format_exc())<br>        return False<br><br><br>try:<br>    import pandas as pd<br>except:<br>    if pip_install(&#39;pandas&#39;):<br>        import pandas as pd<br>try:<br>    import subprocess<br>except:<br>    if pip_install(&#39;subprocess&#39;):<br>        import subprocess<br>try:<br>    import time<br>except:<br>    if pip_install(&#39;time&#39;):<br>        import time<br>try:<br>    import traceback<br>except:<br>    if pip_install(&#39;traceback&#39;):<br>        import traceback<br>try:<br>    from selenium import webdriver<br>    from selenium.webdriver.common.by import By<br>    from selenium.webdriver.support.ui import WebDriverWait<br>    from selenium.webdriver.support import expected_conditions as EC<br>    from selenium.common.exceptions import TimeoutException<br>except:<br>    if pip_install(&#39;selenium&#39;):<br>        from selenium import webdriver<br>        from selenium.webdriver.common.by import By<br>        from selenium.webdriver.support.ui import WebDriverWait<br>        from selenium.webdriver.support import expected_conditions as EC<br>        from selenium.common.exceptions import TimeoutException<br>try:<br>    from webdriver_manager.chrome import ChromeDriverManager<br>except:<br>    if pip_install(&#39;webdriver-manager&#39;):<br>        from webdriver_manager.chrome import ChromeDriverManager<br>    pip_install(&#39;chromedriver_autoinstaller&#39;)</pre><p>Now that we have set up our variables, modules, and libraries, we will need to create functions that execute specific tasks. We will also need to ensure we log every step of the way.</p><p>We will need functions to do these tasks:</p><ul><li>disconnect from the current Wi-Fi connection</li><li>reconnect to the desired Wi-Fi connection</li><li>fill out/submit the guest Wi-Fi registration form</li><li>close the browser once the successful registration landing page is reached</li><li>parent function to call the helper functions above</li></ul><p>This function is used to disconnect from any existing Wi-Fi connection, assuming that your guest registration session has expired and you want to initiate reconnection:</p><pre># function that disconnects from the current wifi<br>def disconnect_from_current_wifi():<br>    try:<br>        # Use the netsh command to disconnect from the connected network<br>        subprocess.run([&#39;netsh&#39;, &#39;wlan&#39;, &#39;disconnect&#39;], check=True)<br>        print(&quot;Disconnected from the current Wi-Fi network&quot;)<br>        return True<br>    except subprocess.CalledProcessError as e:<br>        # log checkpoint<br>        logging.error(<br>            &quot;An error occurred during the disconnection process: %s&quot;, e)<br>        print(&quot;Failed to disconnect from the current Wi-Fi network&quot;)<br>        return False</pre><p>This next function is used to connect to the desired Wi-Fi connection, which uses the global variable of ‘<strong><em>network_name </em></strong>’ we defined earlier.</p><pre>def connect_to_wifi():<br>    try:<br>        # Use the netsh command to connect to the desired network<br>        subprocess.run([&#39;netsh&#39;, &#39;wlan&#39;, &#39;connect&#39;,<br>                       f&#39;name={network_name}&#39;], check=True)<br>        print(f&quot;Connected to desired Wi-Fi network: &#39;{network_name}&#39;&quot;)<br>        return True<br>    except subprocess.CalledProcessError as e:<br>        # log checkpoint<br>        logging.error(<br>            f&quot;Failed to connect to &#39;{network_name}&#39; Wi-Fi network. Please check that the connection is available: %s&quot;, e)<br>        print(<br>            f&quot;Failed to connect to &#39;{network_name}&#39; Wi-Fi network. Please check that the connection is available.&quot;)<br>        return False</pre><p>This function’s purpose is to automatically fill out and submit the guest registration form utilizing Selenium. It uses the HTML element IDs we have defined earlier. We will call this function in another parent function called ‘<strong><em>login_website</em></strong>’ later on.</p><pre>def fill_form(browser, element_name, id, action):<br>    try:<br>        element = WebDriverWait(browser, 15).until(<br>            EC.presence_of_element_located((By.NAME, id))<br>        )<br>        # if the desired action is to type<br>        if action == sks:<br>            element.send_keys(element_name)<br>        # if the desired action is to click/submit<br>        elif action == click:<br>            element.click()<br>    except TimeoutException as e:<br>        # log checkpoint<br>        logging.error(f&quot;Timeout waiting for element: {element_name}, id: {id}&quot;)<br>        logging.error(e)<br>        return False<br>    return True</pre><p>This function is used to close the Chrome browser once the successful landing page of the hotel/company/airport/etc. is reached.</p><pre>def close_browser_when_complete(browser, target_url):<br>    try:<br>        WebDriverWait(browser, 10).until(<br>            lambda x: x.current_url == target_url<br>        )<br>        browser.quit()<br>        print(f&quot;Browser closed after reaching the target URL: {target_url}&quot;)<br>    except TimeoutException as e:<br>        # log checkpoint<br>        logging.error(<br>            &quot;Login failed, guest portal never reached. Browser will close now.&quot;)<br>        logging.error(e)<br>        browser.quit()</pre><p>Moreover, we have essentially completed the steps and functions required to reconnect, fill/submit the guest form, and close the browser when finished.</p><p>We must have a parent function to call all of these steps one by one. Since all guest Wi-Fi registration portals are unique and require different types of information, it is very important to enter and find the HTML element IDs, necessary fields, and types of data for your specific captive portal.</p><pre>def login_website():<br>    try:<br>        browser = webdriver.Chrome()<br>        browser.get((website_link))<br>        fill_form(browser, username, element_for_username, sks)<br>        fill_form(browser, email, element_for_email, sks)<br>        fill_form(browser, phone, element_for_phone, sks)<br>        fill_form(browser, None, element_for_submit_1, click)<br>        fill_form(browser, None, element_for_submit_2, click)<br>        close_browser_when_complete(browser, target_url)<br>        return True<br>    except Exception as e:<br>        # log checkpoint<br>        logging.error(&quot;An error occurred during the login process...&quot;)<br>        logging.error(e)<br>        return False</pre><p>Lastly, we must have a main function in our .py file to execute which will call on the function above:</p><pre>def main():<br>    try:<br>        if disconnect_from_current_wifi():<br>            logging.info(<br>                &quot;Success: Disconnected from the current Wi-Fi network&quot;)<br>            print(&quot;Attempting to reconnect...&quot;)<br>            time.sleep(5)<br>            if connect_to_wifi():<br>                logging.info(&quot;Success: Connected to desired Wi-Fi network&quot;)<br>                time.sleep(5)<br>                if login_website():<br>                    # log checkpoint<br>                    logging.info(<br>                        &quot;Success: Reconnected to Wi-Fi, guest wifi access form complete&quot;)<br>                    return<br>    except Exception as e:<br>        print(f&quot;An error occurred: {e}&quot;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Congratulations! You have automated the login process of your guest Wi-Fi captive portal. Some things to keep in mind:</p><ul><li><strong>Please keep in mind you may need certain permissions from your network provider.</strong></li><li><strong>This macro may not be considered ethical if this macro is used maliciously.</strong></li><li><strong>You may be responsible for any damages/terms of conditions that may be broken using this macro.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d2788d6e785" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Render: How to Deploy a React + Flask Application]]></title>
            <link>https://medium.com/@choihalim/render-how-to-deploy-a-react-flask-application-31f9528b624e?source=rss-4d3fa1a86317------2</link>
            <guid isPermaLink="false">https://medium.com/p/31f9528b624e</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[render]]></category>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Halim Choi]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 20:22:42 GMT</pubDate>
            <atom:updated>2023-09-29T20:42:40.973Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uwex4Tix17iKJuXy" /><figcaption>Photo by <a href="https://unsplash.com/@halacious?utm_source=medium&amp;utm_medium=referral">Hal Gatewood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Render is a cloud platform that makes it easy to deploy and manage web applications. In this tutorial, we’ll walk through the process of deploying a web application that consists of a React frontend and a Flask Python backend on Render. This combination of technologies is popular for building modern web applications due to their flexibility and scalability.</p><h3>Prerequisites</h3><p>Before we begin, make sure you have the following:</p><ol><li>A Render account (sign up at <a href="https://render.com/">Render</a>).</li><li>A Git repository that contains your production-ready React frontend and Flask Python backend code.</li><li>Node.js and npm installed on your local machine for React development.</li><li>Python and pip installed on your local machine for Flask development.</li></ol><h3>Step 1: Set up the React Frontend</h3><p>Clone your React frontend repository to your local machine if you haven’t already:</p><pre>git clone &lt;frontend-repo-url&gt;<br>cd &lt;frontend-repo-directory&gt;</pre><p>Navigate to your React app’s directory and install the necessary dependencies:</p><pre>cd frontend<br>npm install</pre><p>Build the React app for production:</p><pre>npm run build</pre><p>Now, you should have a build directory containing your production-ready React frontend.</p><h3>Step 2: Setting Up Your Flask Python Backend</h3><p>Clone your Flask Python backend repository to your local machine if you haven’t already:</p><pre>git clone &lt;backend-repo-url&gt;<br>cd &lt;backend-repo-directory&gt;</pre><p>Create a virtual environment and activate it:</p><pre>python -m venv venv<br>source venv/bin/activate  # On Windows, use &#39;venv\Scripts\activate&#39;</pre><p>Install the required Python packages:</p><pre>pip install -r requirements.txt</pre><p>Verify that your Flask app runs locally without issues:</p><pre>python app.py</pre><p>Your Flask backend should now be running locally at <a href="http://localhost:5000.">http://localhost:5000</a>.</p><h3>Step 3: Deploying on Render</h3><p>Log in to your Render account and create a new web service.</p><p>On the “Add a New Service” page, choose the following settings:</p><ul><li>Environment: Docker</li><li>Build Command: Leave it empty</li><li>Start Command: ./start.sh (we will create this script in the next step)</li><li>Environment Variables: Add any environment variables required for your application.</li></ul><p>Click the “Create Service” button.</p><p>Render will provide you with a Git repository URL for your service. Add this as a remote to your backend and frontend repositories:</p><pre>git remote add render &lt;render-git-url&gt;</pre><p>Create a file called Dockerfile in your backend directory with the following content:</p><pre># Use the official Python image as the base image<br>FROM python:3.8-slim<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy the requirements file into the container<br>COPY requirements.txt .<br><br># Install the required Python packages<br>RUN pip install -r requirements.txt<br><br># Copy the rest of the application code into the container<br>COPY . .<br><br># Expose the port that your Flask app listens on<br>EXPOSE 5000<br><br># Start the Flask app<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>Create a file called start.sh in your backend directory with the following content:</p><pre>#!/bin/bash<br>exec gunicorn -b 0.0.0.0:5000 app:appbash</pre><p>Commit your changes and push them to the Render remote:</p><pre>git add .<br>git commit -m &quot;Add Dockerfile and start script&quot;<br>git push render main</pre><p>Render will automatically build and deploy your Flask Python backend. Now, let’s configure the frontend. In your frontend directory, create a file called render.yaml with the following content:</p><pre>buildCommand: npm run build<br>publishDir: build</pre><p>Commit the render.yaml file and push your changes to the Render remote for the frontend:</p><pre>git add .<br>git commit -m &quot;Add render.yaml&quot;<br>git push render main</pre><p>Render will build and deploy your React frontend.</p><p>Once both services are deployed, Render will provide you with a live URL where you can access your application.</p><p>Congratulations! You have successfully deployed a React frontend and Flask Python backend application on Render. You can now access your web application on the provided URL. Render also offers automatic scaling and other deployment features, making it a great choice for hosting modern web applications.</p><p>Check out my personal project below called “HalfWay” deployed on Render, which provides an efficient solution to meetups by creating mid points between users’ locations.</p><p><a href="https://halfway.onrender.com/">https://halfway.onrender.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31f9528b624e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Authenticating and Authorizing Users in Flask Applications]]></title>
            <link>https://medium.com/@choihalim/python-authenticating-and-authorizing-users-in-flask-applications-2db06fd2fcb5?source=rss-4d3fa1a86317------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db06fd2fcb5</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[bcrypt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Halim Choi]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 05:54:34 GMT</pubDate>
            <atom:updated>2023-06-29T05:54:34.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RNz-QpM5SePBaNv4" /><figcaption>Photo by <a href="https://unsplash.com/@hocza?utm_source=medium&amp;utm_medium=referral">Jozsef Hocza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Authentication/Authorization?</h3><p>Authentication and authorization are essential aspects of building secure web applications. Nearly all modern web applications rely on these features in order to authenticate or authorize users performing specific tasks. Registering an account in an application to see posts created by other users, logging in to view users’ interaction with your posts, or a user updating their profile information are some examples of when and why authentication and authorization are necessary.</p><p>Authentication is the process of verifying users attempting to access an application’s resources. It ensures that users actually own the account they are trying to log into before they are granted access. There are multiple types of authentication methods such as:</p><ul><li>password-based authentication</li><li>multi-factor authentication (2FA - SMS/email verification for enhanced security)</li><li>token-based authentication (server generates unique tokens for users)</li></ul><p>We will be using password-based authentication in our example below.</p><p>Authorization is the process of granting or denying access to certain resources or functionalities within an application. This ensures that users have appropriate roles or permissions to perform specific actions. For example, a user in an application can be an admin who has permissions to delete other users/grant other users admin capabilities or they can be a user who can only create blog posts and comment on other users’ blog posts.</p><h3>Code</h3><p>To begin, let’s set up our ‘config.py’ in order to instantiate the Flask application and set its attributes. In order to set your secret key specific to your Flask application, run the following command in your command prompt or terminal:</p><pre>$ python -c &#39;import os; print(os.urandom(16))&#39;</pre><p>We will use this randomly generated key to set the ‘SECRET_KEY’ of your Flask app.</p><pre># config.py<br><br>from flask import Flask<br>from flask_cors import CORS<br>from flask_migrate import Migrate<br>from flask_sqlalchemy import SQLAlchemy<br>from sqlalchemy import MetaData<br><br># instantiate ap and set attributes<br>app = Flask(__name__)<br>app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;sqlite:///app.db&#39;<br>app.config[&#39;SQLALCHEMY_TRACK_MODIFICATIONS&#39;] = False<br>app.json.compact = False<br><br># define metadata, set up Flask-Migrate for migrations, instantiate db<br>metadata = MetaData(naming_convention={<br>    &quot;fk&quot;: &quot;fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s&quot;,<br>})<br><br>db = SQLAlchemy(metadata=metadata)<br>migrate = Migrate(app, db)<br>db.init_app(app)<br><br># enables Cross-Origin Resource Sharing, allowing requests front-end<br>CORS(app)<br><br># generate a secret key in command prompt using this command:<br># `python -c &#39;import os; print(os.urandom(16))&#39;`<br>app.config[&#39;SECRET_KEY&#39;] = ^YOUR_SECRET_KEY_HERE^</pre><p>Next, we must set up our ‘models.py’ which will contain a User class to store user data using SQLAlchemy.</p><pre># models.py<br>from config import db<br><br>class User(db.Model):<br>    __tablename__ = &quot;users&quot;<br><br>    id = db.Column(db.Integer, primary_key=True)<br>    username = db.Column(db.String, unique=True, nullable=False)<br>    password = db.Column(db.String, nullable=False)<br>    created_at = db.Column(db.DateTime, server_default=db.func.now())</pre><p>In a file called ‘app.py’ we will set up the following routes for sign up, login, logout, and authorization. We will be utilizing Flask’s session object in order to store data associated with a specific user session across multiple requests. This information, stored on the server-side, will persist and be accessible while the user is logged into the application. In order to add a layer of encryption and security, we will be using ‘bcrypt’ to hash users’ passwords whenever an account is created. Instead of storing the user passwords in plaintext in the application’s database, we will be storing hashed passwords which will be compared to the user’s actual password during authentication.</p><pre># app.py <br><br>from flask import Flask, request, make_response, session<br>import bcrypt<br><br># import configurations from config.py<br>from config import app, db<br><br># importing the users table from database<br>from models import User<br><br># route for sign up<br>@app.route(&#39;/signup&#39;, methods=[&quot;POST&quot;])<br>def signup():<br>    if request.method == &quot;POST&quot;:<br>        rq = request.get_json()<br>        username = rq[&#39;username&#39;]<br>        password = rq[&#39;password&#39;]<br><br>        # password hashing/salting using bcrypt<br>        salt = bcrypt.gensalt()<br>        hashed_password = bcrypt.hashpw(password.encode(&#39;utf-8&#39;), salt)<br><br>        new_user = User(<br>            username=username,<br>            password=hashed_password.decode(&#39;utf-8&#39;),<br>        )<br>        if new_user:<br>            db.session.add(new_user)<br>            db.session.commit()<br>            session[&#39;user_id&#39;] = new_user.id<br>            return make_response(new_user.to_dict(), 201)<br>        else:<br>            return {&#39;errors&#39;: [&#39;Invalid username or password. Please try again.&#39;]}, 401<br><br># route for login<br>@app.route(&#39;/login&#39;, methods=[&quot;POST&quot;])<br>def login():<br>    if request.method == &quot;POST&quot;:<br>        rq = request.get_json()<br>        # find the user with the corresponding username<br>        user = User.query.filter(User.username.like(f&quot;%{rq[&#39;username&#39;]}%&quot;)).first()<br><br>        # check the password with the hashed password in our database<br>        if user and bcrypt.checkpw(rq[&#39;password&#39;].encode(&#39;utf-8&#39;), user.password.encode(&#39;utf-8&#39;)):<br>            session[&#39;user_id&#39;] = user.id<br>            return make_response(user.to_dict(), 200)<br>        else:<br>            return {&#39;errors&#39;: [&#39;Invalid username or password. Please try again.&#39;]}, 401<br><br># route for logout<br>@app.route(&#39;/logout&#39;, methods=[&quot;DELETE&quot;])<br>def logout():<br>    if request.method == &quot;DELETE&quot;:<br>        session[&#39;user_id&#39;] = None<br>        response = make_response(&#39;&#39;, 204)<br>        return response<br><br># route for authorization<br>@app.route(&#39;/authorize&#39;)<br>def authorize():<br>    user_id = session.get(&#39;user_id&#39;)<br>    if not user_id:<br>        return {&#39;errors&#39;: &#39;You must be logged in to do that. Please log in or sign up.&#39;}, 401<br>    else:<br>        user = User.query.filter(User.id == user_id).first()<br>        if user:<br>            return make_response(user.to_dict(), 200)<br><br># run the server using this command: python app.py<br>if __name__ == &#39;__main__&#39;:<br>    app.run(port=5555, debug=True)</pre><p>Remember to make necessary migrations or revisions using these commands</p><pre># to set up Flask-Migrate<br>$ flask db init migrations<br><br># create an initial empty revision<br>$ flask db revision -m &#39;Create DB&#39;<br><br># run these commands to track your modifications made in models.py<br>$ flask db revision --autogenerate -m &#39;&lt;descriptive message&gt;&#39;<br>$ flask db upgrade head</pre><p>Lastly, run the server using the following command</p><pre>$ python app.py</pre><h3>Accessing API endpoints</h3><p>Now that you’ve set up your endpoints for authentication and authorization you can test them by using tools such as Postman or Thunder Client. The app should be running on port 5555. These are the created endpoints along with their request methods.</p><pre># signup - POST<br>http://localhost:5555/signup<br><br># login - POST<br>http://localhost:5555/login<br><br># logout - DELETE<br>http://localhost:5555/logout<br><br># authorize - GET<br>http://localhost:5555/authorize</pre><p>Example: JSON Body for /signup</p><pre>{<br>  &quot;username&quot;: &quot;bob&quot;,<br>  &quot;password&quot;: &quot;ross&quot;<br>}</pre><p>Once all the endpoints have been tested, you can connect this to the front-end to create a full-stack application with user authentication and authorization!</p><p>There are many different methods for establishing user authentication and authorization. Here are some helpful resources to learn more about them:</p><ul><li><a href="https://www.digitalocean.com/community/tutorials/how-to-add-authentication-to-your-app-with-flask-login">How To Add Authentication to Your App with Flask-Login | DigitalOcean</a></li><li><a href="https://flask-authorize.readthedocs.io/en/latest/#:~:text=Flask%2DAuthorize%20is%20a%20Flask,of%20logic%20for%20enforcing%20permissions">Flask-Authorize - Flask-Authorize 0.2.6 documentation</a></li><li><a href="https://pypi.org/project/bcrypt/">bcrypt</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db06fd2fcb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Building RESTful APIs with Flask and SQLAlchemy]]></title>
            <link>https://medium.com/@choihalim/python-building-restful-apis-with-flask-and-sqlalchemy-4bd0997bae3a?source=rss-4d3fa1a86317------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bd0997bae3a</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[restful-api]]></category>
            <dc:creator><![CDATA[Halim Choi]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 04:32:55 GMT</pubDate>
            <atom:updated>2023-06-09T15:20:24.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2EcKQtcM6DJ_wFdQ" /><figcaption>Photo by <a href="https://unsplash.com/@ignat_dolomanov?utm_source=medium&amp;utm_medium=referral">Ignat Dolomanov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Flask?</h3><p>Flask is a powerful web framework used for building web applications using Python. This framework is well known for its simplicity and lightweight functionality, making it a popular choice for developers. Flask is also extremely modular, allowing developers to add or remove components as needed. Therefore, it is highly customizable and adaptable to different project requirements. Below are some of the key features and benefits of using Flask.</p><h3>Key Features</h3><ul><li>Lightweight — designed to be lightweight, focusing on core functionality which gives developers the choice to add additional libraries they see fit</li><li>Routing — easy to handle different endpoints and HTTP methods with a mechanism that allows developers to map URLs to Python functions</li><li>Web-server development — includes a built-in development server, making it easy to test and run your application during development</li><li>Extensions — consists of helpful extensions that provide additional functionality, such as database integration, user authentication, and form validation</li></ul><h3>Set up</h3><p>Before use, you must install Flask using pip, the Python package manager.</p><p>You can use this command to install or update Flask using pip.</p><blockquote>*note: you may need to install additional dependencies throughout this example</blockquote><pre>$ pip install -U Flask</pre><h3>Example</h3><p>In this example, we will be creating a RESTful API for a User Class.</p><p>First, create a “models.py” file which will contain the User model.</p><h4>models.py</h4><pre># models.py<br>from flask_sqlalchemy import SQLAlchemy<br><br>db = SQLAlchemy()<br><br>class User(db.Model):<br>    __tablename__ = &#39;users&#39;<br>    id = db.Column(db.Integer, primary_key=True)<br>    username = db.Column(db.String(50), unique=True, nullable=False)<br>    email = db.Column(db.String(100), unique=True, nullable=False)<br><br>    def to_dict(self):<br>        return {<br>            &#39;id&#39;: self.id,<br>            &#39;username&#39;: self.username,<br>            &#39;email&#39;: self.email<br>        }</pre><p>Additionally, create a “app.py” file to follow along with the example below.</p><p>We want to include our imports and set up our Flask app to communicate with our chosen database. Here, we’re using SQLAlchemy.</p><h4>app.py</h4><pre># app.py (1/2)<br>from flask import Flask, request, jsonify<br>from flask_restful import Api, Resource<br>from flask_sqlalchemy import SQLAlchemy<br>from flask_cors import CORS<br>from flask_migrate import Migrate<br><br>from models import db, User<br><br>app = Flask(__name__)<br># applies CORS headers to all routes, enabling resources to be accessed<br>CORS(app)<br>app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;sqlite:///app.db&#39;<br>app.config[&#39;SQLALCHEMY_TRACK_MODIFICATIONS&#39;] = False<br>app.json.compact = False<br><br>migrate = Migrate(app, db)<br>db.init_app(app)<br><br>db = SQLAlchemy(app)<br>api = Api(app)</pre><p>Next, we can implement the create API routes in our “app.py” file using flask_restful and define methods for CRUD (create, read, use, delete)</p><pre># app.py (2/2)<br>class Users(Resource):<br><br>    # read<br>    def get(self, user_id=None):<br>        if user_id:<br>            user = User.query.get(user_id)<br>            if not user:<br>                return {&#39;error&#39;: &#39;User not found&#39;}, 404<br>            return {&#39;user&#39;: user.to_dict()}, 200<br>        else:<br>            users = User.query.all()<br>            return {&#39;users&#39;: [user.to_dict() for user in users]}, 200<br><br>    # create<br>    def post(self):<br>        data = request.get_json()<br>        username = data.get(&#39;username&#39;)<br>        email = data.get(&#39;email&#39;)<br>        if not username or not email:<br>            return {&#39;error&#39;: &#39;Username and email are required&#39;}, 400<br>        new_user = User(username=username, email=email)<br>        db.session.add(new_user)<br>        db.session.commit()<br>        return {&#39;message&#39;: &#39;User added successfully&#39;}, 201<br><br>    # update<br>    def put(self, user_id):<br>        user = User.query.get(user_id)<br>        if not user:<br>            return {&#39;error&#39;: &#39;User not found&#39;}, 404<br>        data = request.get_json()<br>        username = data.get(&#39;username&#39;)<br>        email = data.get(&#39;email&#39;)<br>        if not username or not email:<br>            return {&#39;error&#39;: &#39;Username and email are required&#39;}, 400<br>        user.username = username<br>        user.email = email<br>        db.session.commit()<br>        return {&#39;message&#39;: &#39;User updated successfully&#39;}, 200<br><br>    # delete<br>    def delete(self, user_id):<br>        user = User.query.get(user_id)<br>        if not user:<br>            return {&#39;error&#39;: &#39;User not found&#39;}, 404<br>        db.session.delete(user)<br>        db.session.commit()<br>        return {&#39;message&#39;: &#39;User deleted successfully&#39;}, 200<br><br># use api.add_resource to add the paths<br>api.add_resource(Users, &#39;/users&#39;, &#39;/users/&lt;int:user_id&gt;&#39;)<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(port=5555, debug=True)</pre><h3>Generating the Database</h3><p>Here are some helpful commands to run in order to generate and update the tables in your database.</p><pre># to set up Flask-Migrate<br>$ flask db init migrations<br><br># create an initial empty revision<br>$ flask db revision -m &#39;Create DB&#39;<br><br># run these commands to track your modifications made in models.py<br>$ flask db revision --autogenerate -m &#39;&lt;descriptive message&gt;&#39;<br>$ flask db upgrade head</pre><p>Before we can get our server running, we forgot one important step which is to create the actual users! We want to also make a “seed.py” file to populate the database with some fake data using the Faker library.</p><h4>seed.py</h4><pre># seed.py<br>from faker import Faker<br>from app import app<br>from models import db, User<br><br>fake = Faker()<br>with app.app_context():<br>    print(&quot;Starting seed...&quot;)<br>    User.query.delete()<br>    new_users = []<br>    for _ in range(20):<br>        username = fake.user_name()<br>        email = fake.email()<br>        new_user = User(username=username, email=email)<br>        new_users.append(new_user)<br>    db.session.add_all(new_users)<br>    db.session.commit()<br>    print(&quot;Successfully seeded&quot;)</pre><p>Make sure to run the seed file with the following command:</p><pre>$ python seed.py</pre><p>Finally, since we have set our app to “port=5555” you can run the following command to run the server:</p><pre>$ python app.py</pre><p>You should see the server has started and can view the data with the following URLs:</p><pre># all users<br>http://localhost:5555/users<br><br># user by id<br>http://localhost:5555/users/&lt;int:user_id&gt;</pre><p>You can test the API using tools such as ThunderClient (VSCode extension) or Postman to conveniently to test, debug, validate, ensure API endpoints are working correctly.</p><p>To conclude, Flask provides the necessary tools and libraries to handle routing, request handling, and response generation. Combined with libraries such as SQLAlchemy, Flask seamlessly work with Object-Relational Mapping toolkits to provide a complete API solution. Flask is an extremely useful framework for building lightweight, simple, yet scalable web applications.</p><p>Here are some helpful resources to learn more about Flask and SQLAlchemy:</p><ul><li><a href="https://flask.palletsprojects.com/en/2.3.x/">Welcome to Flask - Flask Documentation (2.3.x)</a></li><li><a href="https://flask-restful.readthedocs.io/en/latest/">Flask-RESTful - Flask-RESTful 0.3.10 documentation</a></li><li><a href="https://docs.sqlalchemy.org/en/20/">SQLAlchemy 2.1 Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bd0997bae3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: Decorating Code with Decorators]]></title>
            <link>https://medium.com/@choihalim/python-decorating-code-with-decorators-eca57f164e68?source=rss-4d3fa1a86317------2</link>
            <guid isPermaLink="false">https://medium.com/p/eca57f164e68</guid>
            <category><![CDATA[first-class-object]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[code-reusability]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Halim Choi]]></dc:creator>
            <pubDate>Fri, 19 May 2023 04:34:04 GMT</pubDate>
            <atom:updated>2023-05-19T04:35:26.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g0F0D1pdNu-cSwGz" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>What is a decorator in Python?</strong></h4><p>Python decorators are a versatile and powerful tool that can greatly enhance the functionality of code. A decorator is a design pattern that allows developers to change the behavior of a function or class without directly modifying its source code. It is a higher-order function and class, which receives a function or class as an input and returns it with added modifications or improvements. Decorators enable developers to <em>wrap</em> another function, extending the behavior of the wrapped function, without permanently altering it. To better our understanding of decorators, we first must discuss the concept of functions being first class objects in Python.</p><h4><strong>Python Functions are First Class Objects</strong></h4><p>In Python, functions are considered first class objects which means that functions have the following properties:</p><ul><li>are instances of the Object type</li><li>can be stored in a variable</li><li>used or passed as parameters to other functions</li><li>can return functions from other functions</li><li>can store them in data structures</li></ul><h3>Function Decorators</h3><pre>def example_decorator(func):<br>    def wrapper(name):<br>        print(&quot;This is before function execution...&quot;)<br>        result = func(name)<br>        print(&quot;This is after function execution...&quot;)<br>        return result<br>    return wrapper<br><br>@example_decorator<br>def greet(name):<br>    print(f&quot;Hello, {name}!&quot;)<br><br>greet(&quot;Joe&quot;)</pre><p>As shown above, decorators are denoted by the “<strong>@decorator_name</strong>” syntax placed above function declarations. When the decorated function is called, it is actually the modified version provided by the decorator that gets executed.</p><pre>Before function execution<br>Hello, John!<br>After function execution</pre><h3>Chaining</h3><p>In Python, decorators can be chained, allowing developers to apply multiple decorators to a single function in a sequential manner. Each decorator adds its own functionality or modifications to the function.</p><pre>def stars(func):<br>    def inner(*args, **kwargs):<br>        print(&quot;*&quot; * 20)<br>        func(*args, **kwargs)<br>        print(&quot;*&quot; * 5)<br>    return inner<br><br>def dashes(func):<br>    def inner(*args, **kwargs):<br>        print(&quot;-&quot; * 15)<br>        func(*args, **kwargs)<br>        print(&quot;-&quot; * 10)<br>    return inner<br><br>@stars<br>@dashes<br>def printer(msg):<br>    print(msg)<br><br>printer(&quot;Hello&quot;)</pre><p>The decorators <strong>@stars</strong> and <strong>@dashes </strong>both modify the original printer function. Initially, the stars decorator is applied first by printing 20 stars then calls the <strong>inner</strong> function within the <strong>dashes</strong> function, consequently printing 15 dashes. Then, the original function prints the word “Hello” passed as a parameter which then calls the following<strong> </strong>print function from the <strong>inner</strong> function of <strong>dashes</strong>, printing the next 10 dashes. Lastly, the following print function from the <strong>inner</strong> function of <strong>stars</strong> is invoked, printing the last 5 stars.</p><pre>******************** # 20 stars<br>--------------- # 15 dashes<br>Hello # &quot;Hello&quot;<br>---------- # 10 dashes<br>***** # 5 stars</pre><h3>Class Decorators</h3><p>Decorators can also be used in the context of classes, also allowing developers to modify or enhance the behavior of a class by wrapping it with another class. In a similar fashion as function decorators, you use the “<strong>@decorator_name</strong>” syntax above the class declaration. Then, a decorator function takes the original class as an argument and returns a new class with added modifications.</p><pre>def decorator(cls):<br>    # Define a new class that extends the original class<br>    class DecoratedClass(cls):<br>        # Add a new attribute<br>        new_attribute = &quot;This is an added attribute&quot;<br>        <br>        # Create a new method<br>        def new_method(self):<br>            print(&quot;This is a new method&quot;)<br>            <br>        # Override an existing method<br>        def original_method(self):<br>            super().existing_method()<br>            print(&quot;This is an enhanced existing method&quot;)<br><br>    # return the new decorated class<br>    return DecoratedClass<br><br># Use the @ syntax to add the decorator<br>@decorator<br>class OriginalClass:<br>    def original_method(self):<br>        print(&quot;This is the original method&quot;)<br><br># Create an instance of the decorated class<br>instance = OriginalClass()<br><br>print(instance.new_attribute) # Print the newly created attribute<br>instance.new_method() # Execute the newly created method<br>instance.original_method() # Call the existing and enhanced method</pre><p>The code above would output the following:</p><pre>This is an added attribute<br>This is a new method<br>This is the original method<br>This is an enhanced existing method</pre><p>Class decorators are extremely useful since it allows to add new functionality to existing classes without directly altering its source code.</p><p><strong>Use Cases for Decorators</strong></p><p>The following are just some of the many use cases for decorators:</p><ul><li><strong>error handling</strong>: handle error logic across multiple functions</li><li><strong>logging</strong>: add logging functionality to track and record execution of certain code segments</li><li><strong>timing</strong>: measure execution time of functions</li><li><strong>validation</strong>: validate inputs or outputs and ensure conditions or constraints are met</li><li><strong>limiting</strong>: limit API rate to prevent overuse</li></ul><p>By leveraging the concept of functions as first-class objects, decorators enable the modification and extension of functions and classes through a simple and elegant syntax. Whether it’s adding additional behavior, chaining multiple decorators, or enhancing existing classes, decorators provide flexibility and reusability in code design.</p><p>Here are some helpful sources to learn more about Python Decorators:</p><ul><li><a href="https://docs.python.org/3/glossary.html#term-decorator">Glossary</a></li><li><a href="https://builtin.com/software-engineering-perspectives/python-class-decorator">Using Python Class Decorators</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFsAPt_9Bf3U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFsAPt_9Bf3U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFsAPt_9Bf3U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c17f2ab4a608d0357e962b3a17fc635/href">https://medium.com/media/8c17f2ab4a608d0357e962b3a17fc635/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eca57f164e68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS: Building Dynamic Components with Conditional Rendering]]></title>
            <link>https://medium.com/@choihalim/reactjs-building-dynamic-components-with-conditional-rendering-bd85a6ad224a?source=rss-4d3fa1a86317------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd85a6ad224a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ternary-operator]]></category>
            <category><![CDATA[conditional-statements]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Halim Choi]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 17:04:22 GMT</pubDate>
            <atom:updated>2023-04-27T17:44:27.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="react logo" src="https://cdn-images-1.medium.com/max/241/1*YiJSQuE9WCuadBPcWDucIg.png" /><figcaption>Source: <a href="https://reactjs.org/">https://reactjs.org/</a></figcaption></figure><h3><strong>What is Conditional Rendering in React?</strong></h3><p>React is a declarative and open-source front-end JavaScript library used for building efficient user interface components. Conditional rendering is a feature in React that allows developers to render different components or content within components based on certain conditions, states, user inputs, or data availability. It can minimize redundant code by enabling more reusable and dynamic components.</p><p>In order to have components display specific results to users depending on different conditions, we can use logical JavaScript syntax such as <em>if/else</em> <em>statements</em>, <em>switch case statements</em>, <em>ternary operators</em>, and the “<em>&amp;&amp;” operators </em>to change what the rendering component will return.</p><p>In the examples below, the <strong>UserList</strong> component is the parent of the <strong>User</strong> component. In our parent component, we are rendering child components which will receive props of name (string) and isVerified (boolean).</p><h3><strong>if/else</strong></h3><pre>function User({ name, isVerified }) {<br>  if(isVerified) {<br>    return &lt;li className=&quot;user&quot;&gt;{name}⭐️&lt;/li&gt;;<br>  }<br>  return &lt;li className=&quot;user&quot;&gt;{name}&lt;/li&gt;;<br>}<br><br>export default function UserList() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;List of Users:&lt;/h1&gt;<br>      &lt;ul&gt;<br>        &lt;User<br>          name={&quot;John&quot;}<br>          isVerified={false}<br>        /&gt;<br>        &lt;User<br>          name={&quot;Mary&quot;}<br>          isVerified={true}<br>        /&gt;<br>        &lt;User<br>          name={&quot;Ryan&quot;}<br>          isVerified={false}<br>        /&gt;<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>If the <strong>isVerified</strong> prop for the user is <strong>true</strong>, then the User component will return a “⭐️” next to the user’s name.</p><h3><strong>switch</strong></h3><pre>function User({ name, isVerified }) {<br>  switch(isVerified) {<br>    case true:<br>      return &lt;li className=&quot;user&quot;&gt;{name}⭐️&lt;/li&gt;;<br>    case false:<br>      return &lt;li className=&quot;user&quot;&gt;{name}&lt;/li&gt;;<br>  }<br>}</pre><p>The same logic can be expressed in a switch case statement shown above.</p><h3><strong>ternary</strong></h3><pre>function User({ name, isVerified }) {<br>  return (<br>    &lt;li className=&quot;user&quot;&gt;<br>      {isVerified ? name + &quot;⭐️&quot; : name} <br>    &lt;/li&gt;<br>  );<br>}</pre><p>The ternary operator is extremely useful in reducing redundancy and producing cleaner code shown by the code above.</p><pre>// ternary operator syntax<br>condition ? truthyExpression : falsyExpression</pre><h3>&amp;&amp;</h3><pre>function User({ name, isVerified }) {<br>  return (<br>    &lt;li className=&quot;user&quot;&gt;<br>      {name} {isVerified &amp;&amp; &quot;⭐️&quot;} <br>    &lt;/li&gt;<br>  );<br>}</pre><p>Lastly, using the &amp;&amp; operator is another method of writing less code to achieve the same logical outcome. If <strong>isVerified</strong> is equal to true, then the star will be displayed. Otherwise, only <strong>name</strong> will be displayed.</p><p>Conditional rendering is an essential feature in ReactJS since it allows developers to create interactive and dynamic UI components. Without conditional rendering, it would be significantly more difficult to create reusable components that can adapt to different scenarios and conditions.</p><p>Here are some helpful sources to learn more about conditional rendering:</p><ul><li><a href="https://react.dev/learn/conditional-rendering">Conditional Rendering - React</a></li><li><a href="https://legacy.reactjs.org/docs/conditional-rendering.html">Conditional Rendering - React</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator">Conditional (ternary) operator - JavaScript | MDN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd85a6ad224a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: How Promises Are Kept]]></title>
            <link>https://medium.com/@choihalim/javascript-how-promises-are-kept-5e4b90eb1137?source=rss-4d3fa1a86317------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4b90eb1137</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <dc:creator><![CDATA[Halim Choi]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 22:55:21 GMT</pubDate>
            <atom:updated>2023-05-19T04:36:23.046Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript: How Promises are Kept</h3><figure><img alt="pinky promise" src="https://cdn-images-1.medium.com/max/1024/0*pDbZm8Dv34CKFhS0" /><figcaption>Photo by <a href="https://unsplash.com/@andrewwwpetrov?utm_source=medium&amp;utm_medium=referral">Andrew Petrov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>What is a Promise?</strong></p><p>In JavaScript, a promise is an object that represents either the success or failure of an asynchronous operation (a process that runs in the background without hindering execution of other code).</p><p>Promises have a “state” property and a corresponding “result.”</p><p><strong>States:</strong></p><blockquote><em>Pending —</em> initial or working state, undefined, neither fulfilled nor rejected</blockquote><blockquote><em>Fulfilled — </em>operation is completed with success, resulting a value</blockquote><blockquote><em>Rejected—</em>operation has failed, resulting an error object</blockquote><p><strong>Why do we need Promises?</strong></p><p>Promises are useful in asynchronous JavaScript operations where callbacks within other callbacks are required to be executed. This conundrum of having a recursive structure of callbacks is commonly known as <em>callback hell</em>. To prevent this, promises allow each function to start executing when the previous function finishes its execution.</p><p><strong>How do we use Promises?</strong></p><pre>Promise.then(successCallback, failureCallback)</pre><p>The <em>.then()</em> method takes in two optional arguments: a callback for success (value) and a callback for failure (error). It returns a new Promise object, allowing users to chain calls to other Promise methods.</p><p><strong>Example (Success):</strong></p><pre>const myPromise = new Promise((resolve, reject) =&gt; {<br>  resolve(&quot;Success!&quot;);<br>});<br><br>myPromise.then(<br>  (value) =&gt; {<br>    console.log(value); // Success!<br>  },<br>  (error) =&gt; {<br>    console.error(error);<br>  },<br>);</pre><p>In the example above, the Promise would be fulfilled and execute the console.log(value) resulting in “Success!”</p><p><strong>Example (Error):</strong></p><pre>const myPromise = new Promise((resolve, reject) =&gt; {<br>  reject(new Error(&quot;Error!&quot;));<br>});<br><br>myPromise.then(<br>  (value) =&gt; {<br>    console.log(value);<br>  },<br>  (error) =&gt; {<br>    console.error(error); // Error!<br>  },<br>);</pre><p>In this example above, the Promise would be fulfilled and execute the console.error(error) resulting in “Error: Error!”</p><p>There are many different ways Promises can be used in order to deal with an asynchronous action’s eventual success or failure.</p><p>Here are some resources I found useful to learn about JavaScript Promises:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">Using promises - JavaScript | MDN</a></li><li><a href="https://www.w3schools.com/js/js_promise.asp">W3Schools.com</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">Promise.prototype.then() - JavaScript | MDN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4b90eb1137" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>