<?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 sophie on Medium]]></title>
        <description><![CDATA[Stories by sophie on Medium]]></description>
        <link>https://medium.com/@sophiashovkovy?source=rss-a040c7ff5ab8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*J6j_YEcyt01Gdb-uWe-w2A@2x.jpeg</url>
            <title>Stories by sophie on Medium</title>
            <link>https://medium.com/@sophiashovkovy?source=rss-a040c7ff5ab8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:02:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sophiashovkovy/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[How to Build an LED Display of Time Until Train Arrival Using a Raspberry Pi]]></title>
            <link>https://medium.com/@sophiashovkovy/how-to-build-an-led-display-of-time-until-train-arrival-using-a-raspberry-pi-c3dc45fe28fd?source=rss-a040c7ff5ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3dc45fe28fd</guid>
            <dc:creator><![CDATA[sophie]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 17:18:32 GMT</pubDate>
            <atom:updated>2024-10-11T17:19:25.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*qoV7V35FXV9dIPpzejUwIw.gif" /></figure><p>Python tutorial on how to create an LED display of time until local train arrival using a Raspberry Pi. <a href="https://github.com/sshovkov/raspberry-train/blob/main/README.md">GitHub Link</a>.</p><h4>Materials</h4><ul><li><strong>Raspberry Pi Zero W or WH with a power supply</strong>. I chose the Pi Zero W because was affordable, wireless, and minimal. I bought <a href="https://www.amazon.com/gp/product/B0748MBFTS/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&amp;psc=1">a starter kit on Amazon</a> that included the power supply and other accessories. In hindsight, I wish I’d gotten <a href="https://www.amazon.com/DIGISHUO-Pi-Zero-WH-Pre-Soldered/dp/B0BWT2CBJT/ref=sr_1_6?crid=ZA9CDEWRLORW&amp;keywords=raspberry%2Bpi%2Bzero%2Bwh&amp;qid=1697548570&amp;sprefix=raspberry%2Bpi%2Bzero%2Bwh%2Caps%2C108&amp;sr=8-6&amp;ufe=app_do%3Aamzn1.fos.006c50ae-5d4c-4777-9bc0-4513d670b6bc&amp;th=1">this kit</a> with a Raspberry Pi Zero WH because of the <a href="https://www.adafruit.com/product/3708">pre-soldered GPIO header</a>. When I first started this project, I didn’t realize the Zero W would require me to solder the pins myself.</li><li><strong>&gt;= 4GB MicroSD card and adapter</strong>. You can buy <a href="https://www.amazon.com/gp/product/B09VG5M4WV/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&amp;psc=1">one with the Raspberry Pi OS pre-installed</a> or install the <a href="https://www.raspberrypi.com/software/">operating system</a> on a blank one.</li><li><strong>Display screen</strong>. I chose the <a href="https://www.amazon.com/gp/product/B07FFV537V/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&amp;psc=1">HiLetgo MAX7219 Dot Matrix Module</a>. This came with 5 female-to-female jumper wires that connect the Pi to the display.</li></ul><h4>Setup and Development</h4><p>I opted for a headless setup and enabled SSH, which I documented <a href="https://github.com/sshovkov/raspberry-train/blob/main/setup.md">here</a>.</p><p>The MTA provides real-time subway data via their <a href="https://api.mta.info/#/subwayRealTimeFeeds">API</a>. Each endpoint returns a GTFS blob, which is a compressed binary format based on protocol buffers specific to transit schedules.</p><pre>A2A2#Èñ±©Èñ±©&quot;R16N8Ê&gt;<br>A2A2#¢ò±©¢ò±©&quot;R15N8Ê&gt;<br>A2A2#ó±©ó±©&quot;R14N8Ê&gt;<br>A2A2#°ô±©°ô±©&quot;R13N8Ê&gt;<br>G2G2#õ±©õ±©&quot;R11N8Ê&gt;<br>G2G2# ö±© ö±©&quot;R60N8Ê&gt;<br>D2D2#ã÷±©ã÷±©&quot;G21N8Ê&gt;<br>D2D2#êø±©êø±©&quot;G20N8Ê&gt;<br>D2D2#âù±©âù±©&quot;G19N8Ê&gt;<br>D2D2#¼ú±©¼ú±©&quot;G18N8Ê&gt;</pre><p>To read this format of response, I used the gtfs-realtime-bindings library and parsed it as a FeedMessage.</p><pre>from google.transit import gtfs_realtime_pb2<br>feed = gtfs_realtime_pb2.FeedMessage()<br>response = requests.get(<br> API_ENDPOINT, headers={&quot;x-api-key&quot;: os.environ[&quot;MTA_API_KEY&quot;]}<br>)<br>feed_json = feed.FromString(response.content)<br>for entity in feed_json.entity:<br> …</pre><p>feed_json outputs a readable format where each entity is a distinct type of real-time data. In my case, each entity is a <a href="https://developers.google.com/transit/gtfs-realtime/guides/trip-updates">trip update</a> consisting of one or more stop_time_update’s. Each <a href="https://developers.google.com/transit/gtfs-realtime/reference#message-stoptimeupdate">StopTimeUpdate</a> is the real-time update for arrival and/or departure events at a given stop.</p><pre>entity {<br>  id: &quot;000047R&quot;<br>  trip_update {<br>    trip {<br>      trip_id: &quot;113950_R..S&quot;<br>      route_id: &quot;R&quot;<br>      start_time: &quot;18:59:30&quot;<br>      start_date: &quot;20231015&quot;<br>    }<br>    stop_time_update {<br>      stop_id: &quot;G08S&quot;<br>      arrival {<br>        time: 1697410770<br>      }<br>      departure {<br>        time: 1697410770<br>      }<br>    }</pre><p>To find the relevant StopTimeUpdate for my local train, I had to first find the respective stop_id for my station.</p><p>This took some digging through MTA docs, but I finally found the stops.txt file nested inside of the <a href="http://web.mta.info/developers/data/nyct/subway/google_transit.zip">New York City Transit Subway download link</a>. The stops.txt file contains the stop_id’s for all Subway stations and I found mine by searching for the street number.</p><p>To retrieve the relevant StopTimeUpdate, I iterated over each entity in the feed_json object and for each entity, iterated further through the stop_time_update objects within the trip_update field. When a stop_time_update was found where the stop_id matched my predefined STOP_ID, I appended the stop_time_update to a list that I sorted by the arrival timestamp.</p><pre>feed_json = feed.FromString(response.content)<br><br>stop_time_update_arrivals = [<br>    stop_time_update<br>    for entity in feed_json.entity<br>    for stop_time_update in entity.trip_update.stop_time_update<br>    if stop_time_update.stop_id == STOP_ID<br>]<br><br>sorted_arrivals = sorted(stop_time_update_arrivals, key=lambda x: x.arrival.time)<br>To get the time remaining until the next arrival, I calculated the difference in `sorted_arrivals[0].arrival.time` and `now()`. I also added a check that re-runs the calculation with `sorted_arrivals[1]` if the time remaining is &lt; 2 minutes, the amount of time it takes me to get to the subway.</pre><h4>Running the program on the Raspberry Pi</h4><p>Once I had the program working locally, it was time to test the functionality on the Raspberry Pi. I found a couple of different approaches to get my files running on the Pi:</p><p>1. Copy the files from local to Pi<br>2. Git clone repo in Pi<br>3. Use the Remote — SSH VSCode extension</p><p>I chose method #2, allowing me to edit the project locally and simply git pull on my Raspberry Pi to retrieve the latest version. Option #3 would’ve been ideal (and a cleaner git history), but my Raspberry Pi’s architecture is ARMv6l while the Remote — SSH VSCode extension only supports ARMv7l (AArch32) Raspbian Stretch/9+ (32-bit) or ARMv8l (AArch64) Ubuntu 18.04+ (64-bit). You can determine your Raspberry Pi’s architecture by running uname -m in the shell.</p><p>To setup the project on the Raspberry Pi —</p><ol><li>In your local project once you’ve installed all the necessary packages, run pip freeze &gt; requirements.txt. A requirements.txt file will be created, listing all the dependencies for your project.</li><li>Commit and push code to a Github repo.</li><li>SSH into the Raspberry Pi.</li><li>Run git clone &lt;url&gt;. This creates a project directory on your Raspberry Pi. If the repo is private, you will need to enter your username and create a <a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic">Personal Access Token</a> in Github to use as the password.</li><li>Create a Python virtual environment python3 -m venv myenv. Remember that your Raspberry Pi is not as powerful as your computer and this step may take a few minutes.</li><li>Activate the virtual environment source myenv/bin/activate.</li><li>Copy your local .env to the Pi using the command. My .env file contains the MTA API key and my local stop_id. This command should be run outside of the Raspberry Pi shell: scp path/to/your/local/.env pi@raspberry_pi_ip_address:/path/to/remote/directory.</li><li>Run pip install -r requirements.txt to install all packages listed in the requirements.txt file.</li><li>Run python3 main.py to run the script</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*NweYrDx_LmCHolN9.png" /><figcaption>This is prior to adding the code to display the text on the dot matrix module and setting up the cron job.</figcaption></figure><h4>Connecting LED MAX7219 Display to Raspberry Pi</h4><p>Given this was my first time working with a Raspberry Pi, I did a little bit of research first before attempting to connect my Pi to the MAX7219 Dot Matrix Module.</p><p>The MAX7219 Dot Matrix Module has 5 pins on the side labeled VCC, GND, DIN, CS, and CLK. Each pin has a purpose and needs to be wired to the <a href="https://pinout.xyz/pinout/pin19_gpio10/">correct pin on the Raspberry Pi</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G_pqO5TvKcj4irCX.jpg" /></figure><p>At this point I realized I’d bought a Raspberry Pi model that required me to solder the 40-pin GPIO header to the Pi myself. In hindsight, I should’ve bought the Zero WH with a pre-soldered GPIO header. I had never soldered something but decided to give it a try.</p><p>I posted my plea in a local Buy Nothing Facebook group and a kind neighbor lent me all the necessary equipment. You just need a soldering iron, solder wire, and desoldering wick in case you make a mistake.</p><p>I learned how to solder with <a href="https://www.youtube.com/watch?v=8Z-2wPWGnqE">this YouTube video</a>. I prepped my workspace, set up shop near an open window, and wore an n95 mask and blue light glasses as makeshift goggles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*it_guvruu2j4tPV-.JPG" /></figure><p>The result was not perfect, but it did work. I found that the flat head tip produced the optimal conical shape. When I connected the wires to the LED display, the dots promptly lit up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eyWvM2aBBkq26t0c.jpeg" /></figure><p>To enable the display, I used the SPI library. Once the LED display is wired to the Raspberry Pi, SSH into your Raspberry Pi and run sudo raspi-config to enable the SPI interface. Navigate to “Interfacing Options” &gt; “SPI” and enable SPI. Reboot your Pi with sudo reboot after making changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/0*K2pSfPUeYHDfe8kq.png" /></figure><p>To display text, I used the <a href="https://luma-led-matrix.readthedocs.io/en/latest/python-usage.html#x8-led-matrices">Luma library</a>, a display driver for the MAX7219. I also found that the LCD_FONT was the perfect font face and size for my 8x8 module.</p><pre>from luma.led_matrix.device import max7219<br>from luma.core.interface.serial import spi, noop<br>from luma.core.legacy import text<br>from luma.core.legacy.font import proportional, LCD_FONT<br>from luma.core.render import canvas<br>...<br>def display_minutes(minutes):<br>    serial = spi(port=0, device=0, gpio=noop())<br>    device = max7219(<br>        serial,<br>        cascaded=4,<br>        block_orientation=90,<br>        rotate=0,<br>        blocks_arranged_in_reverse_order=True,<br>    )<br><br>    message = f&quot;{minutes} MIN&quot;<br><br>    with canvas(device) as draw:<br>        text(draw, (3, 1), message, fill=&quot;white&quot;, font=proportional(LCD_FONT))</pre><p>To set up a cron job (i.e., enable your code to run on a schedule), SSH into your Raspberry Pi and run sudo crontab -e to open the Crontab for editing. Inside the crontab file, add the desired cron job entry to schedule the Python script. Note: the sudo in sudo crontab -e will set the cron job for the root user.</p><pre>* * * * * /home/sophiashovkovy/raspberry-train/myenv/bin/python /home/sophiashovkovy/raspberry-train/main.py &gt;&gt; /home/sophiashovkovy/cron.log 2&gt;&amp;1</pre><p>This line schedules the job to run every minute. It includes a path to the Python interpreter that will be used to run the script and a path to the Python script that will be executed by the cron job.</p><p>&gt;&gt; /home/sophiashovkovy/cron.log 2&gt;&amp;1 redirects the stdout and stderr of the cron job to a log file that I can review when debugging.</p><p>In the end, I had a working LED display of the minutes remaining until the next train arrived at my local subway station. I moved it to the entryway table in my apartment and have been using it to time my exit perfectly, getting to wait in the comfort of my home until it’s time to get directly on the train.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*nRICFBlNWQ8YOl0y.gif" /></figure><h4>Resources</h4><ul><li><a href="https://github.com/sshovkov/raspberry-train/blob/main/README.md">GitHub Link</a></li><li><a href="https://api.mta.info/#/subwayRealTimeFeeds">MTA subway realtime feed</a> (sign-in to view)</li><li><a href="https://developers.google.com/transit/gtfs-realtime/examples/python-sample">GTFS Python example</a></li><li><a href="https://pinout.xyz/pinout/pin19_gpio10/">Raspberry Pi Zero W Pinout</a></li><li><a href="https://luma-led-matrix.readthedocs.io/en/latest/python-usage.html#x8-led-matrices">Luma driver for MAX7219</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3dc45fe28fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your first web application with Flask, Python, PostgreSQL, and SQLAlchemy — for beginners]]></title>
            <link>https://medium.com/@sophiashovkovy/build-your-first-web-application-with-flask-python-postgresql-and-sqlalchemy-for-beginners-84470101eba9?source=rss-a040c7ff5ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/84470101eba9</guid>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[programming-tutorials]]></category>
            <dc:creator><![CDATA[sophie]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 13:06:47 GMT</pubDate>
            <atom:updated>2024-02-10T01:33:15.893Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Your First Web App with Python, Flask, PostgreSQL, and SQLAlchemy</h3><p>This is a macOS tutorial for beginners on how to build a simple Flask API with Python, PostgreSQL, and SQLAlchemy.</p><p>You will setup a simple development environment in VS Code, create a Python virtual environment, and build a starter Flask application that will use PostgreSQL as a database and SQLAlchemy to query a database table.</p><h4><strong>Setup a Python virtual environment</strong></h4><p>First, <a href="https://code.visualstudio.com/learn/get-started/basics">download and install</a> VS Code.</p><p>Open VS Code and use the keyboard shortcut cmd + shift + P to open the editor commands. Select Shell Command: Install ‘code’ in PATH. This will allow you to use code . to open VS Code.</p><p>Open the terminal and run the following commands to create your a workspace called MyFirstApp.</p><pre>mkdir MyFirstApp<br>cd MyFirstApp<br>code .</pre><p>In MyFirstApp, create a new file titled app.py with the following code and hit run.</p><pre>print(&#39;Hello, World!&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gKnpraCJaDwuCBSOxg9sFw.gif" /></figure><p>If you see “Hello, World!” printed in the terminal, you’re on the right track. Now we need a Python virtual environment. A Python virtual environment creates an isolated instance where you can install modules and set a Python version that is specific to this instance. For this project, we’ll use python3.</p><p>First run brew install pyenv to install pyenv, which will let you easily create virtual environments. Run python3 -m venv myenv to create the virtual environment wheremyenv is any name you want. Click “Yes” when you see the pop-up to select this environment for the workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*Mxl4oD60UG6P_6hbPu7-Dw.png" /></figure><p>To activate the Python environment, run source myenv/bin/activate or kill the terminal by clicking the trash can icon and re-run the Python file. You will know it’s activated if your path in the terminal is preceded with (myenv).</p><h4>Install Flask</h4><p>Flask is a web application framework and provides a way for web servers to pass requests to web applications.</p><p>To install, run the following command in the terminal</p><pre>pip install Flask</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gi3m3c7r_DCnadq91Xo4jQ.gif" /></figure><p>Now we’re ready to do a basic test on our development environment. In app.py, remove any existing code and implement the following:</p><pre>from flask import Flask<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def hello_world():<br>    return &#39;Hello, World!&#39;</pre><p>A breakdown of each line —</p><ol><li>from flask import Flask imports the Flask module</li><li>app = Flask(__name__) creates a new Flask application instance called app. The __name__ parameter is a special Python variable that represents the name of the current module.</li><li>@app.route(&#39;/&#39;) is a decorator that associates the URL route &#39;/&#39; (the root URL) with the following function. It tells Flask that when a user visits the root URL, the associated function should be executed.</li><li>def hello_world(): defines a function called hello_world(). This function will be executed when a user visits the root URL.</li><li>return &#39;Hello, World!&#39; is a line inside the hello_world() function that specifies the response that the server will send back to the client. In this case, it will return the string &#39;Hello, World!&#39;.</li></ol><p>In the terminal, navigate to the project root directory and run export FLASK_APP=app.py. Run flask run --debug to start your Flask application. The --debug flag ensures you have instant reloading when making changes to your app. You should see something along the lines of</p><pre> * Serving Flask app &#39;app.py&#39;<br> * Debug mode: on<br>WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.<br> * Running on http://127.0.0.1:5000<br>Press CTRL+C to quit<br> * Restarting with stat<br> * Debugger is active!<br> * Debugger PIN: 857-132-268</pre><blockquote>When you want to quit the Flask application, use ctrl + c</blockquote><p>Navigate to <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000</a> in the browser, this is your local host, and you will see the text returned in the hello_world() function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*iDs3RXT4G_enrSwPIb4dRQ.png" /></figure><p>Try experimenting with creating more routes to see different behavior. For example, try adding the following route and function, then navigating to <a href="http://127.0.0.1:5000/sophia">http://127.0.0.1:5000/</a>&lt;your-name&gt;</p><pre>@app.route(&#39;/&lt;string:name&gt;&#39;)<br>def birthday(name):<br>    return &#39;Hello, &#39; + name + &#39;!&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MZf3139YsuB9Ia7UQqd8Cg.png" /></figure><p>Other helpful resources for Flask app routing</p><ul><li><a href="https://pythonbasics.org/flask-tutorial-routes/">https://pythonbasics.org/flask-tutorial-routes/</a></li><li><a href="https://hackersandslackers.com/flask-routes/">https://hackersandslackers.com/flask-routes/</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-create-your-first-web-application-using-flask-and-python-3">https://www.digitalocean.com/community/tutorials/how-to-create-your-first-web-application-using-flask-and-python-3</a></li></ul><h4>Connect a PostgreSQL database</h4><p>PostgreSQL is a free and open-source relational database management system. The easiest way to install on Mac is to follow the download instructions on <a href="https://postgresapp.com/">https://postgresapp.com</a>.</p><p>Once you launch the app, you’ll see 3 servers: postgres, &lt;your-user&gt;, and template1. Hit “Start” and double click any one of these to open the database. When you’re in a database, you’ll use psql to run commands and queries.</p><p>The following is a reference to a few of the most handy commands</p><ul><li>List all databases — \l</li><li>Switch to a database — \c &lt;db-name&gt;</li><li>List database tables in a database — \dt</li><li>Describe a table — \d</li><li>Quit psql — \q</li></ul><p>Currently if you run \dt you’ll get “Did not find any relations” since we don’t have any tables yet. We’ll make some in a bit.</p><p>To connect the PostgreSQL database with our Python code we’ll use SQLAlchemy, a SQL toolkit that we’ll use to query our database. In the terminal, run the following commands to install it.</p><pre>pip install -U Flask-SQLAlchemy<br>pip install psycopg2</pre><p>Then kill the terminal and save app.py to reload the virtual environment. To establish a connection between app.py and a PostgreSQL server, add the following to your Python file</p><pre>from flask_sqlalchemy import SQLAlchemy<br><br>app = Flask(__name__)<br><br>app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;postgresql://localhost:&lt;your-port-number&gt;/&lt;your-user-server&gt;&#39;<br>app.config[&#39;SECRET_KEY&#39;] = &quot;random string&quot;<br>db = SQLAlchemy(app)<br>...</pre><p>&lt;your-port-number&gt; can be found in the Postgres App and &lt;your-user-server&gt; is the name of the Postgres server associated with your user. For example, &#39;postgresql://localhost:5432/postgres&#39;</p><p>To create your first table, add the following to app.py</p><pre>class Person(db.Model):<br>    id = db.Column(db.Integer, primary_key=True)<br>    first_name = db.Column(db.String(50), nullable=False)<br>    last_name = db.Column(db.String(50), nullable=False)<br>    email = db.Column(db.String(50), nullable=False)<br>    age = db.Column(db.Integer, nullable=False)<br><br>    def repr(self):<br>        return &#39;&lt;Name %r&gt;&#39; % self.first_name<br>    <br>    def __init__(self, first_name, last_name, email, age):<br>        self.first_name = first_name<br>        self.last_name = last_name<br>        self.email = email<br>        self.age = age<br>    <br>with app.app_context():<br>    db.create_all()</pre><p>And run the following code to create the Person table in our Postgres database.</p><pre>Flask shell<br>db.create_all()</pre><blockquote><em>To exit the Flask shell, run </em><em>quit()</em></blockquote><p>To verify a table was created, open the Postgres App and double click on the server that you established a connection to. Run \dt and you should see the Person relation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6WNpYyJwiKYtlV-ibriyg.png" /></figure><p>Try running a query, SELECT * FROM person; to see all rows in the Person table. Currently this will be empty, but as we add to the table you’ll see this populate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QBgMIpqOHPzdXb5_Tftkg.png" /></figure><p>We’re going to expand on the foundation we’ve created to build a simple web application that lets a user keep a record of people. We’ll want to provide the user with functionality to add a person, delete a person, and view all people on the list.</p><p>When building web applications, it’s important to separate business logic from presentation logic. Business logic is the backend of the application. it’s how we handle user requests and talking to the database. Presentation logic is the frontend and handles presenting data to the user. In Flask, this means having our functions render templates of HTML that structure the data in a presentable way to the user.</p><p>To start, let’s update the hello_world() function to render a simple HTML file that will act as the home screen for the user.</p><p>First, create a templates folder in the project and create a file within it called home_screen.html.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Home Screen&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;Home screen&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>from flask import Flask, render_template<br>...<br>@app.route(&#39;/&#39;)<br>def hello_world():<br>    return render_template(&#39;home_screen.html&#39;)</pre><p>Now when you navigate to <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a> you will see the html rendered</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qmflNJ9k2auzem82GXzEBw.png" /></figure><p>This is the foundation of how we will pass backend logic to the frontend for a user to see and interact with.</p><p>Let’s create a new route at \new that will display an input form on the frontend, that when filled out will add a Person to the database table.</p><pre>@app.route(&#39;/new&#39;)<br>def new_person():<br>    return render_template(&#39;add_person.html&#39;)</pre><p>Similar to home_screen.html, create a new file called add_person.html.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>   &lt;body&gt;<br>      &lt;button onclick=&quot;goToHome()&quot;&gt;Go to Home Screen&lt;/button&gt;<br>      &lt;h3&gt;Add a person&lt;/h3&gt;<br>      &lt;hr/&gt;<br>      <br>      {%- for category, message in get_flashed_messages(with_categories = true) %}<br>         &lt;div class = &quot;alert alert-danger&quot;&gt;<br>            {{ message }}<br>         &lt;/div&gt;<br>      {%- endfor %}<br>      <br>      &lt;form action=&quot;&quot; method=&quot;post&quot;&gt;<br>         &lt;label for=&quot;first_name&quot;&gt; First name &lt;/label&gt;&lt;br&gt;<br>         &lt;input type=&quot;text&quot; name=&quot;first_name&quot; placeholder=&quot;Johnny&quot; /&gt;&lt;br&gt;<br><br>         &lt;label for=&quot;last_name&quot;&gt; Last name &lt;/label&gt;&lt;br&gt;<br>         &lt;input type=&quot;text&quot; name=&quot;last_name&quot; placeholder=&quot;Appleseed&quot; /&gt;&lt;br&gt;<br><br>         &lt;label for=&quot;email&quot;&gt; Email &lt;/label&gt;&lt;br&gt;<br>         &lt;input type=&quot;text&quot; name=&quot;email&quot; placeholder=&quot;johnny@gmail.com&quot; /&gt;&lt;br&gt;<br><br>         &lt;label for=&quot;age&quot;&gt; Age &lt;/label&gt;&lt;br&gt;<br>         &lt;input type=&quot;text&quot; name=&quot;age&quot; placeholder=&quot;25&quot; /&gt;&lt;br&gt;<br><br>         &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;<br>      &lt;/form&gt;<br>      &lt;script&gt;<br>         function goToHome() {<br>           window.location.href = &#39;/&#39;;<br>         }<br>       &lt;/script&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><p>I won’t cover HTML syntax here, but essentially we are creating an input form that has text fields for first name, last name, email, and age.</p><p>The action attribute specifies the URL or destination where the form data will be sent when the user submits the form. When set to an empty string (&quot;&quot;), the form data will be sent to the current URL where the form is rendered (in this case \new).</p><p>The method attribute specifies the HTTP method to be used when submitting the form data.</p><p>When you navigate to <a href="http://127.0.0.1:5000/new">http://127.0.0.1:5000/new</a>, you should see a simple input form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OrLA2Dt03ZuSz-mVQoeazw.png" /></figure><p>Currently if you hit submit, nothing will happen. We need to fill out our new_person() function to handle a POST request (since that is the action performed on submit in the HTML) and commit the new information to the database.</p><pre>from flask import Flask, render_template, request, redirect, flash, url_for<br>...<br>@app.route(&#39;/new&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def new_person():<br>    if request.method == &#39;POST&#39;:<br>        if not request.form[&#39;first_name&#39;] or not request.form[&#39;last_name&#39;] or not request.form[&#39;email&#39;] or not request.form[&#39;age&#39;]:<br>            flash(&#39;Please enter all the fields&#39;, &#39;error&#39;)<br>        else:<br>            new_person = Person(request.form[&#39;first_name&#39;], request.form[&#39;last_name&#39;], request.form[&#39;email&#39;], request.form[&#39;age&#39;])<br>            db.session.add(new_person)<br>            db.session.commit()<br><br>            flash(&#39;Form added successfully!&#39;)<br>            return redirect(url_for(&#39;hello_world&#39;))<br>    return render_template(&#39;add_person.html&#39;)</pre><p>Now when you submit you will be redirected to the home screen. Query the Postgres server to see the new record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*LKqFMjdL3En1HtBShZayzQ.png" /></figure><p>That covers the basics of how to create a simple Flask web application that uses PostgreSQL and SQLAlchemy to work with a database.</p><p>Try building out the functions for viewing all people records and deleting a person record on your own.</p><p>You can find <a href="https://github.com/sshovkov/flask-web-app-tutorial/tree/main">the solution files here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84470101eba9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Stripe Saves Payment Methods]]></title>
            <link>https://medium.com/@sophiashovkovy/how-stripe-saves-payment-methods-f3e03823e8e2?source=rss-a040c7ff5ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3e03823e8e2</guid>
            <category><![CDATA[payment-method]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[stripe-integration]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[stripe-payment]]></category>
            <dc:creator><![CDATA[sophie]]></dc:creator>
            <pubDate>Thu, 29 Sep 2022 16:32:26 GMT</pubDate>
            <atom:updated>2023-11-29T17:01:03.775Z</atom:updated>
            <content:encoded><![CDATA[<p>Stripe treats credit and debit cards as Source objects. When a customer pays with card, the card is saved as a payment method on the customer and Stripe automatically sets it as the default. You can find it on the Customer object under [&#39;default_source&#39;].</p><p>ACH, or bank transfers, are PaymentMethod objects. When a customer pays with ACH it’s saved as a payment method on the customer but Stripe will <em>not</em> automatically set it as the default. Additional steps are necessarily to set an ACH payment as the default, after which it will be on the Customer object under [&#39;invoice_settings&#39;][&#39;default_payment_method&#39;]. PaymentMethod objects are designed specifically for subscriptions and invoices, hence why they show up on the Customer under invoice_settings, not default_source.</p><p>Side note — ACH <em>credit</em> transfers are treated as Source objects. The main difference is that an ACH credit transfer is initiated by the sender of funds (typically a bank), whereas an ACH debit transfer is initiated by the receiver of funds, where the bank receives a payment request by the payee, and then sends the funds per request.</p><figure><img alt="Diagram of how payment methods get saved to the Customer object by Stripe" src="https://cdn-images-1.medium.com/max/1024/1*SQMqOlWkNICipPpXKWiy-w.png" /><figcaption>Diagram of how payment methods get saved to the Customer object by Stripe</figcaption></figure><h3><a href="https://stripe.com/docs/api/sources">Source</a> objects</h3><p><em>Allow you to accept a variety of payment methods (card and ACH). They represent a customer’s payment instrument.</em></p><ul><li>The default source is automatically selected if you make a charge request using the customer parameter without specifying a source.</li><li>Default source may be used for all charges.</li></ul><h3><a href="https://stripe.com/docs/api/payment_methods">PaymentMethod</a> objects</h3><p><em>Represent your customer’s payment instruments. You can </em><strong><em>use them with </em></strong><a href="https://stripe.com/docs/payments/payment-intents"><strong><em>PaymentIntents</em></strong></a><em> to collect payments or save them to Customer objects to store instrument details for future payments.</em></p><ul><li>Is attached to a PaymentIntent to represent the <a href="https://stripe.com/docs/payments/intents">states of a payment lifecycle</a>.</li><li>This is where new product and feature development is focused.</li><li>The default PaymentMethod is only usable for subscriptions and invoices</li></ul><h3>Try it yourself in test mode</h3><p><strong>Simulate customer paying with credit/debit card</strong></p><ol><li>Enable test mode and create a customer with no payment method</li><li><a href="https://stripe.com/docs/api/customers/retrieve?lang=python">Retrieve the customer</a> and verify that [‘default_source’] and [‘invoice_settings’][‘default_payment_method’] are both null</li><li>Invoice the customer and pay the invoice with a test card. The payment method will be saved to the customer, <em>and set as the default. </em>You can verify this by retrieving the customer again.[‘default_source’] will show the payment method.</li></ol><p><strong>Simulate customer paying with ACH</strong></p><ol><li>Enable test mode and create a customer with no payment method</li><li><a href="https://stripe.com/docs/api/customers/retrieve?lang=python">Retrieve the customer</a> and verify that [‘default_source’] and [‘invoice_settings’][‘default_payment_method’] are both null</li><li>Invoice the customer and pay the invoice with ACH. The payment method will be saved to the customer, <em>but not as the default. </em>You can verify this by retrieving the customer again.[‘default_source’] and [‘invoice_settings’][‘default_payment_method’] are both still null</li><li>Set the ACH bank transfer payment method as the default</li><li>Retrieve the customer again and this time the PaymentMethod object will show under [‘invoice_settings’][‘default_payment_method’]. Note that [‘default_source’] is still null</li></ol><p>Despite cards and bank transfers being two different objects, they cannot be set to default at the same time.</p><h3>Don’t want to save payment methods on your customers?</h3><p>You have two options</p><ol><li>Don’t pass the <a href="https://stripe.com/docs/api/payment_intents/create#create_payment_intent-setup_future_usage">setup_future_usage</a> parameter when creating the PaymentIntent. The payment method will not be attached to the customer.</li><li>If you are not creating a PaymentIntent, you can listen for payment_intent.succeeded and <a href="https://stripe.com/docs/api/payment_methods/detach">detach the payment method</a> on the event. Note that in the case where the payment method is ACH bank transfer, the payment method will be initially saved to the Customer until the payment clears.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3e03823e8e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>