<?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 Henry Wu on Medium]]></title>
        <description><![CDATA[Stories by Henry Wu on Medium]]></description>
        <link>https://medium.com/@ihenrywu?source=rss-e0ad32ea0f20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7TTHB2Mu9bxCwD9cx5zKqQ.jpeg</url>
            <title>Stories by Henry Wu on Medium</title>
            <link>https://medium.com/@ihenrywu?source=rss-e0ad32ea0f20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:41:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ihenrywu/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 “Hibernate” Your AWS Project to $5/month (Without Deleting It)]]></title>
            <link>https://medium.com/preprintblog/how-to-hibernate-your-aws-project-to-5-month-without-deleting-it-860d77767882?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/860d77767882</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[save-money]]></category>
            <category><![CDATA[hibernate]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 22:31:08 GMT</pubDate>
            <atom:updated>2026-01-25T22:31:08.742Z</atom:updated>
            <content:encoded><![CDATA[<p>As independent developers, we often have projects that are “done” but not currently active. Leaving them running on AWS burns $40-$50/month unnecessarily. Deleting them feels wrong because you might need them later.</p><p>There is a third option: <strong>Hibernation.</strong></p><p>This guide records exactly how to strip an AWS deployment down to its bare bones — paying only for storage (~less than $5/month) — while keeping the ability to bring it back to life in 30 minutes.</p><h3>The Strategy</h3><p>We aren’t just clicking “Stop.” That doesn’t kill all the costs. We need to:</p><ol><li><strong>Stop Compute</strong> (The biggest cost).</li><li><strong>Release IPs</strong> (The hidden cost).</li><li><strong>Snapshot &amp; Kill Database</strong> (The rigid cost).</li><li><strong>Put up a “Maintenance” sign</strong> (The professional touch).</li></ol><h3>Phase 1: The Shutdown (Cutting Costs)</h3><h3>Step 1: The EC2 Shutdown</h3><p>Stopping the instance is obvious, but it’s only half the battle.</p><ol><li>Go to <strong>EC2 Console</strong> &gt; <strong>Instances</strong>.</li><li>Select your instance &gt; <strong>Instance State</strong> &gt; <strong>Stop Instance</strong>.</li></ol><ul><li><em>Result:</em> You stop paying for CPU/RAM (~$12–20/month savings).</li><li><em>Cost Remaining:</em> You still pay for the EBS volume (disk), which keeps your files safe.</li></ul><h3>Step 2: The “Elastic IP” Trap (Crucial!)</h3><p>AWS charges for public static IPs (Elastic IPs) if they are attached to a stopped instance or unattached entirely.</p><ol><li>Go to <strong>EC2</strong> &gt; <strong>Network &amp; Security</strong> &gt; <strong>Elastic IPs</strong>.</li><li><strong>Disassociate</strong> the IP address first.</li><li><strong>Release</strong> the IP address.</li></ol><ul><li><em>Warning:</em> If you don’t do this, AWS charges ~$3.60/month just for holding the IP.</li><li><em>Note:</em> You will lose this specific IP address. When you restart later, you’ll just generate a new one.</li></ul><h3>Step 3: Deep Freezing the Database (RDS)</h3><p>You can’t just “Stop” an RDS database indefinitely; AWS will auto-restart it after 7 days. To save money, we must delete it safely.</p><ol><li>Go to <strong>RDS</strong> &gt; <strong>Databases</strong>.</li><li>Select your DB &gt; <strong>Actions</strong> &gt; <strong>Take Snapshot</strong>.</li></ol><ul><li>Name it clearly: project-name-final-backup-2026.</li></ul><ol><li>Wait for the snapshot to finish (Status: Available).</li><li>Select the DB &gt; <strong>Actions</strong> &gt; <strong>Delete</strong>.</li></ol><ul><li><strong>Uncheck</strong> “Create final snapshot” (you just made one).</li><li><strong>Uncheck</strong> “Retain automated backups” (waste of money).</li><li>Confirm deletion.</li></ul><p><em>Savings:</em> This kills the hourly DB cost (~$15–30/month) and storage cost. You only pay pennies for the backup file.</p><h3>Step 4: Check for Hidden Fees (NAT Gateways)</h3><p>If you set up a private network (VPC), check for a <strong>NAT Gateway</strong>.</p><ol><li>Go to <strong>VPC Console</strong> &gt; <strong>NAT Gateways</strong>.</li><li>If you see one, <strong>Delete</strong> it.</li></ol><ul><li><em>Warning:</em> These cost ~$30/month even if idle.</li></ul><h3>Step 5: The “Under Maintenance” Page (Optional)</h3><p>Don’t let your domain dead-end.</p><ol><li>Upload a simple index.html (&quot;We are upgrading...&quot;) to <strong>Cloudflare Pages</strong> (Free).</li><li>Point your DNS (CNAME) to the Cloudflare URL.</li></ol><ul><li><em>Benefit:</em> Keeps your SEO alive and looks professional.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LU0zojB1IYpuD-jFnwyEew.png" /></figure><h3>Phase 2: The Revival (Restoring the Project)</h3><p>When the day comes to reactivate the project, here is the reverse process.</p><h3>1. Restore the Database</h3><ol><li>Go to <strong>RDS</strong> &gt; <strong>Snapshots</strong>.</li><li>Select project-name-final-backup-2026.</li><li><strong>Actions</strong> &gt; <strong>Restore Snapshot</strong>.</li></ol><p><em>Crucial:</em> You must ensure the <strong>VPC</strong> and <strong>Security Groups</strong> match your original settings, or your EC2 won’t be able to talk to it.</p><h3>2. Update the App Config</h3><p>Restoring a DB creates a <strong>new Endpoint URL</strong>.</p><ol><li>Wait for the new RDS to start.</li><li>Copy the new <strong>Endpoint</strong> string.</li><li>SSH into your EC2 (once started) and update your .env or config.js file with the new DB host.</li></ol><h3>3. Start EC2 &amp; Re-assign IP</h3><ol><li>Start your EC2 instance.</li><li>Go to <strong>Elastic IPs</strong> &gt; <strong>Allocate Elastic IP</strong>.</li><li><strong>Associate</strong> the new IP to your running instance.</li></ol><h3>4. Update DNS</h3><ol><li>Go to your DNS provider (Route53/Cloudflare).</li><li>Update the A record to point to your new Elastic IP.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=860d77767882" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/how-to-hibernate-your-aws-project-to-5-month-without-deleting-it-860d77767882">How to “Hibernate” Your AWS Project to $5/month (Without Deleting It)</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a “Zero-Cost” Security Logger Using Google Sheets and JavaScript]]></title>
            <link>https://medium.com/preprintblog/how-to-build-a-zero-cost-security-logger-using-google-sheets-and-javascript-3871378e392b?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/3871378e392b</guid>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[fraud-prevention]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[logger]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 06:08:07 GMT</pubDate>
            <atom:updated>2026-01-21T06:08:07.635Z</atom:updated>
            <content:encoded><![CDATA[<p>If you run a membership site or a digital product store (like Shopify), you often have a blind spot: <strong>You don’t know who is actually logging in.</strong></p><p>Shopify shows you sales, but it doesn’t easily show you: <em>“Is User A logging in from Vancouver and London at the same time?”</em> (A classic sign of password sharing).</p><p>To solve this, I built a lightweight <strong>Access Logger</strong> that records the <strong>Time</strong>, <strong>Email</strong>, <strong>IP Address</strong>, <strong>City</strong>, and <strong>Country</strong> of every user who views my content.</p><p>Best of all? It costs <strong>$0</strong> and requires no server setup. It runs entirely on <strong>Google Sheets</strong> and <strong>Vanilla JavaScript</strong>.</p><h3>The Architecture</h3><p>We are using Google Sheets as a “Serverless Database.”</p><ol><li><strong>The Client (Browser):</strong> Fetches the user’s location via a free API (ipapi.co).</li><li><strong>The Beacon:</strong> Sends that data via a simple HTTP GET request to a Google Script.</li><li><strong>The Server (Google Apps Script):</strong> Catches the request and appends a row to the Sheet.</li></ol><h3>Step 1: The Backend (Google Apps Script)</h3><p>First, we need a script that can “listen” for data. Google Apps Script provides a special function called doGet() that runs whenever someone visits the script&#39;s URL.</p><p>Create a new <strong>Google Sheet</strong>. Go to <strong>Extensions</strong> &gt; <strong>Apps Script</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyI8y9w-urJED7TO9sJuew.png" /></figure><p>Paste this code:</p><pre>function doGet(e) {<br>  // 1. Connect to the active sheet<br>  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();<br>  <br>  // 2. Parse the incoming parameters (e.g. ?email=sid@test.com)<br>  var timestamp = new Date();<br>  var email = e.parameter.email;<br>  var ip = e.parameter.ip;<br>  var city = e.parameter.city;<br>  var country = e.parameter.country;<br>  var page = e.parameter.page;<br><br>  // 3. Append the data to the next empty row<br>  sheet.appendRow([timestamp, email, ip, city, country, page]);<br><br>  // 4. Return a &quot;200 OK&quot; text response<br>  return ContentService.createTextOutput(&quot;Logged&quot;).setMimeType(ContentService.MimeType.TEXT);<br>}</pre><h3>Step 2: The Critical Deployment Step</h3><p>This is where most people fail. For your website to talk to your Google Sheet, the script must be publicly accessible (as an API endpoint).</p><p>Click <strong>Deploy</strong> &gt; <strong>New Deployment</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hj95cGQixw9-bOkdBM3-hQ.png" /></figure><p>Select Type: <strong>Web App</strong>.</p><p><strong>Execute as:</strong> Me (Your account).</p><p><strong>Who has access:</strong> <strong>Anyone</strong>.</p><p><em>Note: If you set this to “Only Me,” your website’s JavaScript will be blocked from sending data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IeJA24N1v-kk0n0oELKijA.png" /></figure><p>Click <strong>Deploy</strong> and copy the <strong>Web App URL</strong>.</p><h3>Step 3: The Frontend (The “Beacon”)</h3><p>Now, on your website (Shopify, WordPress, or standard HTML), you add a script that runs when the page loads.</p><p>We use the fetch API twice:</p><ol><li><strong>First Fetch:</strong> Ask ipapi.co &quot;Where am I?&quot; to get the IP and Location.</li><li><strong>Second Fetch:</strong> Send that data to our Google Sheet.</li></ol><p><strong>The “Fire and Forget” Trick:</strong> Note the { mode: &#39;no-cors&#39; } in the code below. Google Scripts don&#39;t like cross-origin requests from browsers. By setting no-cors, we tell the browser: <em>&quot;Send the data, but don&#39;t wait for a response.&quot;</em> This prevents CORS errors in the console.</p><pre>&lt;script&gt;<br>  // 1. Get the User&#39;s Location Data<br>  fetch(&#39;https://ipapi.co/json/&#39;)<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; {<br>      <br>      const userIP = data.ip;<br>      const userCity = data.city;<br>      const userCountry = data.country_name;<br>      // Assume we have the logged-in email from Liquid/PHP/etc.<br>      const userEmail = &quot;{{ customer.email }}&quot;; <br><br>      // 2. The Google Web App URL (From Step 2)<br>      const googleScriptUrl = &quot;YOUR_GOOGLE_SCRIPT_URL_HERE&quot;;<br><br>      // 3. Construct the URL with parameters<br>      const finalUrl = `${googleScriptUrl}?email=${encodeURIComponent(userEmail)}&amp;ip=${userIP}&amp;city=${userCity}&amp;country=${userCountry}&amp;page=ReaderPortal`;<br><br>      // 4. Send the beacon (Fire and Forget)<br>      fetch(finalUrl, { mode: &#39;no-cors&#39; });<br>      <br>      console.log(&quot;Access logged to Google Sheets&quot;);<br><br>    })<br>    .catch(error =&gt; console.log(&quot;Logging failed&quot;, error));<br>&lt;/script&gt;</pre><p>Open your Google Sheet, and you will see rows populating in real-time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1OEzkdnz50rxcvX6kS-NtA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3871378e392b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/how-to-build-a-zero-cost-security-logger-using-google-sheets-and-javascript-3871378e392b">How to Build a “Zero-Cost” Security Logger Using Google Sheets and JavaScript</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Built a Secure “Netflix-Style” eBook reader on Shopify]]></title>
            <link>https://medium.com/preprintblog/how-to-built-a-secure-netflix-style-ebook-reader-on-shopify-fecba3af6075?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/fecba3af6075</guid>
            <category><![CDATA[anti-tamper]]></category>
            <category><![CDATA[locksmith]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[ebooks-online]]></category>
            <category><![CDATA[heyzine]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 00:29:06 GMT</pubDate>
            <atom:updated>2026-01-21T06:12:24.572Z</atom:updated>
            <content:encoded><![CDATA[<p>If you sell digital books, you face a dilemma:</p><ol><li><strong>Send a PDF:</strong> The customer emails it to 50 friends. You lose money.</li><li><strong>Use DRM Software:</strong> The customer hates you because they have to install “Adobe Digital Editions.”</li><li><strong>Build a Custom Platform:</strong> You spend 6 months coding instead of selling.</li></ol><p>I wanted a middle ground: <strong>Zero-install for the user, but high friction for pirates.</strong></p><p>Here is how I built a secure, watermarked, read-only reader using <strong>Shopify</strong>, <strong>Heyzine</strong>, <strong>Locksmith</strong>, and some <strong>custom JavaScript</strong>.</p><h3>The Architecture</h3><p>We are not building a fortress; we are building a fence that is annoying to climb.</p><ul><li><strong>The Content Host:</strong> <strong>Heyzine</strong> (Free/Standard Plan). Converts PDFs into HTML5 Flipbooks that are hard to scrape.</li><li><strong>The Gatekeeper:</strong> <strong>Locksmith</strong> ($12/mo). Protects the page so only “Paid Customers” can enter.</li><li><strong>The Security Layer:</strong> <strong>Custom Liquid + JavaScript</strong>. A dynamic watermark that stamps the user’s <strong>Email + IP Address</strong> directly onto the screen.</li><li><strong>The Logger:</strong> <strong>Google Sheets</strong> (Free). A backend logger to track who is reading and from where.</li></ul><h3>Step 1: The “Un-Downloadable” Book</h3><p>First, I needed a viewer that doesn’t just hand over the .pdf file. I chose <a href="https://heyzine.com/"><strong>Heyzine</strong></a>. It renders the PDF as an HTML5 canvas, making &quot;Right Click &gt; Save As&quot; impossible for average users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJMG-f5MLVxajM0pS-b1sw.png" /></figure><p><strong>Config:</strong></p><ul><li>Upload PDF to Heyzine.</li><li>Go to “Controls” page</li><li><strong>Disable</strong> Download,Share , Print andFullscreen button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r78enJVDMoRbgG8H3z0Krw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1qsZoF1Gw8NtdgqivLLnA.png" /></figure><ul><li>Go to the “Share” button and get the html code</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QF2aoq4vNQ2x9fzm83gtlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWSa6Wx9-uV9tyTlAzjceg.png" /></figure><h3>Step 2: Create the Custom Page Template</h3><p><em>Now, we prepare the empty room in Shopify.</em></p><ul><li>Go to <em>Online Store &gt; Themes &gt; Edit Theme</em>.</li><li>Select <em>Home Page &gt; Pages &gt; Create Template</em>. Name it ebook-reader.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rr4GJlaytxImAZCITrVwQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rel9r-gpCXvUyIWLDvskEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zu2AbslmKXAbDysDh96PRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uf_YkQ_mqRfmbgYtvL2ZWA.png" /></figure><p>Clean up the Template, delete the irrelevant components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzvnCshffvSN2GtuWN32fg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugjlwT7PeaP13-umkIyRcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oG6ULYUbaJIZz94wBB5tOw.png" /></figure><p>Add a <strong>Custom Liquid</strong> section to the template:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK55lwSA1O5KMTCCfSbmTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*pga28yyD9I7wl3K31wNYsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHoCQQAWF-h6aASF5nAERg.png" /></figure><p>Paste the <strong>Code:</strong></p><pre>&lt;style&gt;<br>  /* 1. The Container */<br>  .book-protector-container {<br>    position: relative;<br>    width: 100%;<br>    height: calc(100vh - 100px); <br>    min-height: 600px; <br>    overflow: hidden;<br>    background-color: #333; <br>    display: flex;<br>    justify-content: center;<br>    align-items: center;<br>  }<br><br>  /* 2. The Heyzine Book */<br>  .fp-iframe {<br>    width: 100%;<br>    height: 100%;<br>    border: none;<br>    position: absolute;<br>    top: 0;<br>    left: 0;<br>    z-index: 1; <br>  }<br><br>  /* 3. The Watermark Layer */<br>  .watermark-overlay {<br>    position: absolute;<br>    top: 0;<br>    left: 0;<br>    width: 100%;<br>    height: 100%;<br>    z-index: 999; <br>    pointer-events: none; <br>    display: flex;<br>    flex-wrap: wrap;<br>    align-content: center; <br>    justify-content: center;<br>    overflow: hidden;<br>    opacity: 1 !important; <br>    visibility: visible !important; <br>  }<br><br>  .watermark-text {<br>    font-family: monospace; <br>    font-size: 14px;<br>    font-weight: 700;<br>    color: rgba(255, 0, 0, 0.15); /* Red with 15% opacity */<br>    transform: rotate(-30deg); <br>    margin: 60px; <br>    white-space: nowrap;<br>    user-select: none;<br>    text-align: center;<br>  }<br><br>  /* 4. Safe Fullscreen Button */<br>  #safe-fs-btn {<br>    position: absolute;<br>    top: 60px;<br>    right: 50px;<br>    z-index: 1000; <br>    padding: 8px 16px;<br>    background-color: rgba(0, 0, 0, 0.7);<br>    color: white;<br>    border: 1px solid white;<br>    border-radius: 4px;<br>    cursor: pointer;<br>    font-size: 14px;<br>    font-family: sans-serif;<br>  }<br>  #safe-fs-btn:hover { background-color: black; }<br><br>  /* Fullscreen overrides */<br>  .book-protector-container:fullscreen { height: 100vh; width: 100vw; }<br>  .book-protector-container:-webkit-full-screen { height: 100vh; width: 100vw; }<br>&lt;/style&gt;<br><br>&lt;div class=&quot;book-protector-container&quot; id=&quot;book-wrapper&quot;&gt;<br>  &lt;button id=&quot;safe-fs-btn&quot; onclick=&quot;toggleSafeFullscreen()&quot;&gt;<br>    ⛶ Fullscreen<br>  &lt;/button&gt;<br><br>  &lt;iframe <br>    allowfullscreen=&quot;allowfullscreen&quot; <br>    allow=&quot;clipboard-write&quot; <br>    scrolling=&quot;no&quot; <br>    class=&quot;fp-iframe&quot; <br>    src=&quot;https://heyzine.com/flip-book/cc27753798.html&quot;&gt;<br>  &lt;/iframe&gt;<br><br>  &lt;div class=&quot;watermark-overlay&quot;&gt;<br>    {% if customer %}<br>      {% for i in (1..20) %}<br>        &lt;div class=&quot;watermark-text&quot;&gt;<br>          Licensed to {{ customer.email }} &lt;br&gt;<br>          IP: &lt;span class=&quot;user-ip-display&quot;&gt;Connecting...&lt;/span&gt; | {{ &#39;now&#39; | date: &quot;%Y-%m-%d %H:%M&quot; }}<br>        &lt;/div&gt;<br>      {% endfor %}<br>    {% else %}<br>      {% for i in (1..20) %}<br>        &lt;div class=&quot;watermark-text&quot;&gt;<br>          PREVIEW MODE &lt;br&gt; LOGIN TO VIEW<br>        &lt;/div&gt;<br>      {% endfor %}<br>    {% endif %}<br>  &lt;/div&gt;<br>&lt;/div&gt;<br><br><br>&lt;script&gt;<br>  // --- 1. Fetch IP &amp; Location ---<br>  fetch(&#39;https://ipapi.co/json/&#39;)<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; {<br>      <br>      // Get the data separately<br>      var userIP = data.ip;<br>      var userCity = data.city;<br>      var userCountry = data.country_name;<br><br>      // A. Update the Watermark (IP Only)<br>      const ipSpans = document.querySelectorAll(&#39;.user-ip-display&#39;);<br>      ipSpans.forEach(span =&gt; {<br>        span.innerText = userIP; <br>      });<br><br>      // B. Send to Google Sheet (Split Columns)<br>      {% if customer %}<br>        var userEmail = &quot;{{ customer.email }}&quot;;<br>        // PASTE YOUR GOOGLE URL HERE<br>        var googleScriptUrl = &quot;PASTE_YOUR_GOOGLE_URL_HERE&quot;; <br>        <br>        var finalUrl = googleScriptUrl + <br>                       &quot;?email=&quot; + encodeURIComponent(userEmail) + <br>                       &quot;&amp;ip=&quot; + encodeURIComponent(userIP) + <br>                       &quot;&amp;city=&quot; + encodeURIComponent(userCity) +       // &lt;--- New<br>                       &quot;&amp;country=&quot; + encodeURIComponent(userCountry) + // &lt;--- New<br>                       &quot;&amp;page=ReaderPortal&quot;;<br>        <br>        fetch(finalUrl, { mode: &#39;no-cors&#39; });<br>      {% endif %}<br><br>    })<br>    .catch(error =&gt; {<br>      console.log(&#39;Fetch failed&#39;);<br>      // Fallback<br>      {% if customer %}<br>         var googleScriptUrl = &quot;PASTE_YOUR_GOOGLE_URL_HERE&quot;; <br>         fetch(googleScriptUrl + &quot;?email={{ customer.email }}&amp;ip=Unknown&amp;city=Unknown&amp;country=Unknown&quot;, { mode: &#39;no-cors&#39; });<br>      {% endif %}<br>    });<br><br>  // --- 2. Fullscreen Logic (No Changes) ---<br>  function toggleSafeFullscreen() {<br>    var elem = document.getElementById(&quot;book-wrapper&quot;);<br>    if (!document.fullscreenElement) {<br>      if (elem.requestFullscreen) elem.requestFullscreen();<br>      else if (elem.webkitRequestFullscreen) elem.webkitRequestFullscreen();<br>      else if (elem.msRequestFullscreen) elem.msRequestFullscreen();<br>      document.getElementById(&quot;safe-fs-btn&quot;).innerText = &quot;✖ Exit&quot;;<br>    } else {<br>      if (document.exitFullscreen) document.exitFullscreen();<br>      else if (document.webkitExitFullscreen) document.webkitExitFullscreen();<br>      else if (document.msExitFullscreen) document.msExitFullscreen();<br>      document.getElementById(&quot;safe-fs-btn&quot;).innerText = &quot;⛶ Fullscreen&quot;;<br>    }<br>  }<br><br>  // --- 3. Anti-Tamper Security Logic (No Changes) ---<br>  (function() {<br>    const container = document.querySelector(&#39;.book-protector-container&#39;);<br>    const watermark = document.querySelector(&#39;.watermark-overlay&#39;);<br>    if (!container || !watermark) return;<br><br>    container.addEventListener(&#39;contextmenu&#39;, function(e) { e.preventDefault(); return false; });<br><br>    function restoreWatermark() {<br>      if (!container.contains(watermark)) container.appendChild(watermark);<br>      watermark.style.display = &#39;flex&#39;;<br>      watermark.style.opacity = &#39;1&#39;;<br>      watermark.style.visibility = &#39;visible&#39;;<br>    }<br><br>    const observer = new MutationObserver(function(mutations) {<br>      mutations.forEach(function(mutation) {<br>        if (mutation.removedNodes.length &gt; 0) {<br>          mutation.removedNodes.forEach(node =&gt; {<br>            if (node === watermark || (node.classList &amp;&amp; node.classList.contains(&#39;watermark-overlay&#39;))) {<br>              restoreWatermark();<br>            }<br>          });<br>        }<br>        if (mutation.type === &#39;attributes&#39; &amp;&amp; mutation.target === watermark) restoreWatermark();<br>      });<br>    });<br><br>    observer.observe(container, { childList: true, subtree: true });<br>    observer.observe(watermark, { attributes: true, attributeFilter: [&#39;style&#39;, &#39;class&#39;, &#39;hidden&#39;] });<br>  })();<br>&lt;/script&gt;</pre><p><strong>What this code does:</strong> It wraps the Heyzine iframe in a security container, disabling right-clicks and overlaying the dynamic watermark.</p><p>Note: replace this part with the real link of the heyzine:</p><pre>&lt;iframe <br>    allowfullscreen=&quot;allowfullscreen&quot; <br>    allow=&quot;clipboard-write&quot; <br>    scrolling=&quot;no&quot; <br>    class=&quot;fp-iframe&quot; <br>    src=&quot;https://heyzine.com/flip-book/xxx.html&quot;&gt;<br>  &lt;/iframe&gt;</pre><p><strong>Add the “Spy” Logging (Optional)</strong></p><ol><li>Create a <strong>Google Sheet</strong> script to accept data.</li><li>Paste the code to App Script and get the Web App URL.</li></ol><pre>function doGet(e) {<br>  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();<br>  <br>  var timestamp = new Date();<br>  var email = e.parameter.email;<br>  var ip = e.parameter.ip;<br>  var city = e.parameter.city;<br>  var country = e.parameter.country;<br>  var page = e.parameter.page;<br><br>  // Add the row with separate columns<br>  sheet.appendRow([timestamp, email, ip, city, country, page]);<br><br>  return ContentService.createTextOutput(&quot;Success&quot;).setMimeType(ContentService.MimeType.TEXT);<br>}</pre><p>3. Paste the Web App URL into the Shopify Liquid code, replace PASTE_YOUR_GOOGLE_URL_HERE.</p><p><strong>4. Result:</strong> You now have a real-time log of every IP address accessing your book, allowing you to catch password sharers instantly.</p><h3>Step 3: Configure the Page &amp; Menu (The Hookup)</h3><p><em>Now we connect the template to a real URL and make it accessible.</em></p><ol><li><strong>Create a New Page:</strong></li></ol><p>Go to <em>Online Store &gt; Pages</em> and create a page named “Reader Portal”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dk1jUInquwPheQRl7vg7HQ.png" /></figure><p><strong>2. Assign the Template:</strong></p><p>In the “Reader Portal” page, set the visibility as “Visible” and choose the Template of “ebook-reader”. Then click the Save button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMjMWH0GNiKrzv38g-K9HA.png" /></figure><p><strong>3. Add to Menu:</strong></p><ul><li>Go to <strong>Content </strong>&gt; <strong>Menus</strong></li></ul><p>Select the <strong>Main Menu, </strong>Click <strong>Add menu item</strong> &gt; Name it “reading” &gt; Link it to the “Reader Portal” page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qfa2BQ4Ekurszjtn5Lfww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XLFysxRH6d9q5CVyf7qEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cs3lEDM_pbI8076j-MjZeQ.png" /></figure><p>Then we can see the page in the front page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfjFGlrLm1kstrR2SWBR_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIarNC7z4WDdtUZ9DQnWUw.png" /></figure><h3>Step 4: The Gatekeeper (Locksmith)</h3><p><em>Finally, we lock the door. Right now, your page is secure from piracy, but it is open to the public. We need to ensure only paid customers can enter.</em></p><ol><li><strong>Install Locksmith:</strong></li></ol><p>Install the <a href="https://apps.shopify.com/locksmith?search_id=7776c3e2-85b3-4c38-b883-7a2498650e75&amp;shallow_install_type=search&amp;surface_detail=locksmith&amp;surface_inter_position=1&amp;surface_intra_position=1&amp;surface_type=search"><strong>Locksmith</strong></a> app from the Shopify App Store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MVHYlPchltFBfzgYXCeTA.png" /></figure><p><strong>2. Create a Lock:</strong></p><p>Open Locksmith and search for your page: <strong>“Reader Portal”</strong>. Click the page to create a lock on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUxBRU_EE1JLyWG0KWpHVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cg9KQkbQYGcP-d9ukmwyfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WXVdMNMeTmF5oyFp3EBdg.png" /></figure><p><strong>3. Set the Key (The Condition):</strong></p><p>Click <strong>“Add Key”,</strong></p><p>Choose the condition: <strong>“Has purchased product…”.</strong></p><p>Select your ebook product</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7VIwVKJZi0wzEgsVt4csuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxBbHYJMuJwle3Zds8BhTQ.png" /></figure><p>Get the SKU of your eBook product, you can get it from the end of the link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnF1ZaSgcrefHGcQR7JYzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDHMXXw0m2HAOmffbEo8wA.png" /></figure><p><strong>Configure the “Access Denied” Screen:</strong></p><p>If a stranger tries to visit the URL, what do they see? Set the message to: <em>“You must purchase book to access this library.”</em></p><p><strong>Pro Tip:</strong> Add a button linking directly to the product page so they can buy it immediately!</p><p><strong>The Final Result:</strong></p><ul><li><strong>Stranger:</strong> Clicks “Reading” → Sees Lock Screen → Buys Book.</li><li><strong>Customer:</strong> Clicks “Reading” → Sees the Watermarked Book → Reads securely.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fecba3af6075" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/how-to-built-a-secure-netflix-style-ebook-reader-on-shopify-fecba3af6075">How to Built a Secure “Netflix-Style” eBook reader on Shopify</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Free “Test Website” Using a Subdomain to Safely Test New Features of Your Website]]></title>
            <link>https://medium.com/preprintblog/build-a-free-test-website-using-a-subdomain-to-safely-test-new-features-of-your-website-10a7cadc0653?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/10a7cadc0653</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[subdomain]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[staging]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 06:49:35 GMT</pubDate>
            <atom:updated>2025-11-16T06:49:35.864Z</atom:updated>
            <content:encoded><![CDATA[<p>After launching a website and getting real users, adding new features becomes risky. The first instinct is to “just test directly on the live site,” but that’s a bad idea: any mistake affects real users.</p><p>For a long time, I solved this by creating a <strong>second EC2 instance</strong> just for testing. It worked, but it cost money and felt unnecessary.</p><p>Later, I discovered a much simpler, zero-cost solution:</p><p>You can use the <strong>same EC2 machine</strong> and create a separate <strong>subdomain</strong> (for example staging.mydomain.com) that runs a completely independent copy of your app. This environment is called <strong>staging</strong>.</p><p>The main domain (mydomain.com) continues serving the production code, while your subdomain (staging.mydomain.com) becomes a safe place to test new features online. After everything works well on staging, you deploy the same code to production with confidence.</p><h3>What “Staging” Actually Is</h3><p>Staging is a safe sandbox that behaves like production, but without real users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q19JWgBI-BiWUW01v1LMpA.png" /></figure><p>Both environments run the same app, but completely independently.</p><h3>1. Cloudflare DNS Setup</h3><p>Since my domain is managed by cloudflare, we need to set it up on cloudflare first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHvtH6CmHBfm7qJSqSVYcw.png" /></figure><p>Because Cloudflare only needs to forward traffic to EC2 — the SSL is handled later.</p><h3>2. Nginx Virtual Host for Staging</h3><p>Create a new config:</p><pre>/etc/nginx/conf.d/myapp_staging.conf</pre><p>Contents:</p><pre>server {<br>    server_name staging.mydomain.com;<br><br>    listen 443 ssl;<br>    ssl_certificate     /etc/ssl/cloudflare/mydomain.crt;<br>    ssl_certificate_key /etc/ssl/cloudflare/mydomain.key;<br><br>    location / {<br>        proxy_pass http://127.0.0.1:5001;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}<br><br>server {<br>    listen 80;<br>    server_name staging.mydomain.com;<br>    return 301 https://$host$request_uri;<br>}</pre><p>Then apply changes:</p><pre>sudo nginx -t<br>sudo systemctl restart nginx</pre><h3>3. Gunicorn Service for Staging</h3><p>Create a new systemd service:</p><pre>/etc/systemd/system/gunicorn_myapp_staging.service</pre><p>Contents:</p><pre>[Unit]<br>Description=Gunicorn (Staging) service for MyApp<br>After=network.target<br><br>[Service]<br>User=ec2-user<br>Group=ec2-user<br><br>WorkingDirectory=/var/www/myapp_staging<br><br>ExecStart=/var/www/myapp_staging/venv_myapp_staging/bin/gunicorn \<br>    -w 2 -b 127.0.0.1:5001 &quot;app:create_app()&quot;<br><br>Environment=&quot;FLASK_ENV=staging&quot;<br>Environment=&quot;CURRENT_WEB=myapp_staging&quot;<br>Environment=&quot;PATH=/var/www/myapp_staging/venv_myapp_staging/bin&quot;<br><br>Restart=always<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Enable and start:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl enable gunicorn_myapp_staging<br>sudo systemctl start gunicorn_myapp_staging</pre><h3>4. Folder Structure on EC2</h3><pre>/var/www/myapp/            ← production<br>    .env<br>    venv_myapp/<br>    geoip/<br>    app/<br><br>/var/www/myapp_staging/    ← staging<br>    .env<br>    venv_myapp_staging/<br>    geoip/<br>    app/</pre><p>These directories are independent — deployments won’t cross over.</p><h3>5. GitHub Actions Deployment for Staging</h3><p>Create .github/workflows/deploy_staging.yml:</p><pre>name: Deploy MyApp Staging<br><br>on:<br>  push:<br>    branches:<br>      - staging<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout Repo<br>      uses: actions/checkout@v4<br><br>    - name: Configure AWS<br>      uses: aws-actions/configure-aws-credentials@v2<br>      with:<br>        aws-access-key-id: ${{ secrets.AWS_KEY }}<br>        aws-secret-access-key: ${{ secrets.AWS_SECRET }}<br>        aws-region: us-east-1<br><br>    - name: Setup SSH<br>      run: |<br>        mkdir -p ~/.ssh<br>        echo &quot;${{ secrets.SSH_KEY }}&quot; &gt; ~/.ssh/id_rsa<br>        chmod 600 ~/.ssh/id_rsa<br>        ssh-keyscan -H ${{ secrets.EC2_HOST }} &gt;&gt; ~/.ssh/known_hosts<br><br>    - name: Deploy to EC2 (Staging)<br>      run: |<br>        # Clean or create staging folder<br>        ssh ec2-user@${{ secrets.EC2_HOST }} &lt;&lt; &#39;EOF&#39;<br>        sudo mkdir -p /var/www/myapp_staging<br>        sudo find /var/www/myapp_staging/ -mindepth 1 \<br>          -not -name &#39;.env&#39; \<br>          -not -path &#39;/var/www/myapp_staging/geoip*&#39; \<br>          -exec rm -rf {} +<br>        EOF<br><br>        # Upload new code<br>        rsync -av \<br>          --exclude=&#39;.git&#39; \<br>          --exclude=&#39;.github&#39; \<br>          --exclude=&#39;venv_*&#39; \<br>          -e &quot;ssh -i ~/.ssh/id_rsa&quot; \<br>          ./ ec2-user@${{ secrets.EC2_HOST }}:/var/www/myapp_staging/<br><br>        # Install dependencies<br>        ssh ec2-user@${{ secrets.EC2_HOST }} &lt;&lt; &#39;EOF&#39;<br>        cd /var/www/myapp_staging/<br>        python3 -m venv venv_myapp_staging<br>        source venv_myapp_staging/bin/activate<br>        pip3 install -r requirements.txt<br>        sudo systemctl restart gunicorn_myapp_staging<br>        sudo systemctl restart nginx<br>        EOF</pre><p>Now whenever I push to the <strong>staging branch</strong>, the staging server updates automatically.</p><h3>6. Testing Workflow</h3><p>My development process becomes:</p><ol><li>Write code locally</li><li>Push to staging branch</li><li>Visit <a href="https://staging.mydomain.com/"><strong>https://staging.mydomain.com</strong></a></li><li>If everything works → merge to main</li><li>Production deploys automatically</li></ol><p>This keeps the live site safe. A staging environment gives me:</p><ul><li>A safe playground</li><li>The same EC2, Nginx, Gunicorn, hardware, and OS</li><li>Automatic deployments</li><li>No risk to production data</li></ul><p>Once set up, staging becomes part of the normal workflow and makes development much smoother.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10a7cadc0653" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/build-a-free-test-website-using-a-subdomain-to-safely-test-new-features-of-your-website-10a7cadc0653">Build a Free “Test Website” Using a Subdomain to Safely Test New Features of Your Website</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Automatic Cloud-Based Speech-to-Text (STT) Workflow with Flask and AWS]]></title>
            <link>https://medium.com/preprintblog/a-simple-automatic-cloud-based-speech-to-text-stt-workflow-with-flask-and-aws-d7b5553b0e88?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7b5553b0e88</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[stt]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[aws-transcribe]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 18:56:13 GMT</pubDate>
            <atom:updated>2025-11-03T18:56:13.820Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first built my mock interview platform, I relied entirely on <strong>browser-based Speech-to-Text (STT)</strong> — using webkitSpeechRecognition.</p><p>It worked great in Chrome, but some users found that the microphone or transcription simply didn’t work. For example, if they are in some specific countries, or use some specific browsers such as Firefox.</p><p>That was when I decided to build a <strong>parallel API-based STT system, </strong>one that didn’t depend on browser capability.</p><p>And that became the start of my “<strong>fire-and-forget</strong>” journey: a clean collaboration between <strong>Flask</strong>, <strong>JavaScript</strong>, and <strong>AWS Lambda</strong>, where the browser uploads and moves on while the cloud does all the heavy lifting.</p><h3>The Idea: Fire and Forget</h3><p>The idea is simple:</p><pre>The frontend just uploads the user&#39;s voice to S3 and forgets about it.<br>AWS Lambda takes over, processes it in the background, and stores the result.<br>Later, the browser checks back once in a while to see if the transcript is ready.</pre><p>No waiting. No long API calls. No complex message queues. Just <strong>one upload + two Lambda workers + a simple polling loop</strong>.</p><h3>The Architecture at a Glance</h3><pre>👩‍💻 Browser (User clicks &quot;Start Interview&quot;)<br>    ↓<br>    Flask  →  /generate_batch_presigned_urls<br>              (Generates S3 links + merges with program data)<br>    ↓<br>    Browser receives JSON:<br>        {<br>          &quot;live_question&quot;: [...],<br>          &quot;s3_upload_urls&quot;: [...]<br>        }<br>    ↓<br>    ──▶ User answers Question 1<br>           ↓<br>           JS uploads audio.webm → S3 (via presigned URL)<br>           ↓<br>           ✅ Upload done (browser continues — fire &amp; forget)<br><br>🪣 AWS S3 (New file uploaded)<br>    ↓ (S3 Event Trigger)<br>    ├── Lambda #1 → AWS Transcribe<br>    │        • Converts .webm to text<br>    │        • Saves raw transcript (answer_raw) in s3<br>    │<br>    └── Lambda #2 → DynamoDB<br>             • Updates record:<br>                 answers[n].answer_clean = &quot;final text&quot;<br><br>📦 DynamoDB<br>    ↓<br>    Flask  →  /get_transcript_from_dynamoDB<br>              (Periodically fetches transcript results)<br>    ↓<br>    Browser<br>        • Displays available answers<br>        • Polls until all are ready<br>        • Updates localStorage(&quot;answers&quot;)<br>        • Shows final AI review and summary</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6NDErwBbBrXKJjQnuh73g.png" /></figure><p>This flow turns the <strong>frontend, backend, and cloud</strong> into clear collaborators:</p><ul><li><strong>Frontend (JS)</strong> → Captures, uploads, and moves on</li><li><strong>Flask</strong> → Coordinates uploads and pulls results</li><li><strong>AWS Lambda</strong> → Does the real STT and saving asynchronously</li></ul><p>Everything runs independently — no waiting, no bottlenecks, no blocking calls.</p><h3>AWS Lambda: Two Cloud Workers</h3><p>Lambda functions triggered automatically by S3 event (.wav or .mp4 uploaded). It runs STT (AWS Transcribe) and saves text to DynamoDB.</p><p>Tips for create lambda:</p><ol><li>Remember click ‘Deploy’ after paster your code, otherwise, it won’t auto save.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnUmaSgEfuoaebxrj1wApA.png" /></figure><p>2. Add trigger, so when there is new file upload to s3, it will trigger lambda:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j67J1PhU9L-Zc81noFMxLw.png" /></figure><p>3. set up permission:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzjAJUxGJQBc6A9QlOMyeg.png" /></figure><p>So the lambda can read and write s3, dynamoDB.</p><h3>Backend: Flask as the Coordinator</h3><p>Flask doesn’t do any STT. It simply orchestrates the workflow:</p><p>First, Accepts uploads and returns presigned S3 URLs</p><p>Second, Provides a /get_transcript_from_dynamoDB endpoint for polling</p><p>The philosophy: <strong>Keep Flask light. Let the cloud work.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7b5553b0e88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/a-simple-automatic-cloud-based-speech-to-text-stt-workflow-with-flask-and-aws-d7b5553b0e88">A Simple Automatic Cloud-Based Speech-to-Text (STT) Workflow with Flask and AWS</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Send Emails via Zoho Mail with Python SMTP (for FREE)]]></title>
            <link>https://medium.com/preprintblog/how-to-send-emails-via-zoho-mail-with-python-smtp-for-free-576a37f09f78?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/576a37f09f78</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[free]]></category>
            <category><![CDATA[zoho]]></category>
            <category><![CDATA[smtp]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 05:46:01 GMT</pubDate>
            <atom:updated>2025-04-16T05:46:01.647Z</atom:updated>
            <content:encoded><![CDATA[<p>With the <strong>Zoho Mail Free Plan</strong>, you can create up to <strong>5 custom email addresses</strong> using your domain after verifying it. Once properly configured, these emails can <strong>send messages using SMTP</strong> and integrate with your app or system.</p><h3>1. <strong>Sign up with your personal email address</strong></h3><p>Register for Zoho Mail Free Plan using your personal email here:</p><pre>https://mail.zoho.com/signup?plan=mailPremiumTrial</pre><h3>2. <strong>Verify your custom domain</strong></h3><p>After registering, Zoho will prompt you to verify your domain by adding DNS records.</p><h3>3. <strong>Create up to 5 domain-based email addresses</strong></h3><p>Once verified, you can create up to <strong>5 email addresses</strong> under your domain. One of these users will be assigned premium features.</p><ul><li>Go to <a href="https://admin.zoho.com/">https://admin.zoho.com</a></li><li>Navigate to <strong>Users</strong></li><li>Add a user mailbox (e.g., noreply@yourdomain.com)</li><li>Log in once to activate the account at <a href="https://mail.zoho.com/">https://mail.zoho.com</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5kY2jy7POy_E8q68xddhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9iWRC58_dvZ6HgC17U5pA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gl-TNZmhNWnHo6yXfSpMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEjw1btep6o5oM24__SUCw.png" /></figure><h3>4. <strong>Only the premium user can access the Zoho Mail Admin Panel</strong></h3><p>That user can log in to the admin dashboard at:</p><pre>https://mailadmin.zohocloud.ca/cpanel/home.do</pre><h3>5. <strong>Other users access only the mailbox interface</strong></h3><p>The remaining domain-based users can log in directly at:</p><pre>https://accounts.zohocloud.ca/signin?servicename=AaaServer&amp;serviceurl=%2Fhome%23profile%2Fpersonal</pre><h3>6. Generate an App Password</h3><ul><li>Log in to <a href="https://accounts.zoho.com/">https://accounts.zoho.com</a> as noreply@yourdomain.com</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q0qdK0Ytn62OEGb7AvGcdg.png" /></figure><ul><li>Go to <strong>Security &gt; App Passwords</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-qs3fQ5W6SweEjb59l84Q.png" /></figure><ul><li>Click <strong>Generate New Password</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOWf9CF_LCqnt0MoIlOD3Q.png" /></figure><ul><li>Name it something like SMTP Python</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpgVITxXqKqCr83ROMj05A.png" /></figure><ul><li>Copy the generated password (you won’t see it again)</li></ul><h3>7. Check the email setting by the admin email</h3><ul><li>Log in the admin dashboard at:</li></ul><pre>https://mailadmin.zohocloud.ca/cpanel/home.do</pre><p>get the configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWbucAH7oWi5PFnu-W1-Vw.png" /></figure><h3>8. Use Python to Send Email via SMTP</h3><pre>import smtplib<br>from email.mime.text import MIMEText<br><br>SMTP_SERVER = &quot;smtp.zohocloud.ca&quot;<br>SMTP_PORT = 587  # or use 465 for SSL<br>EMAIL = &quot;noreply@yourdomain.com&quot;<br>APP_PASSWORD = &quot;your_app_password_here&quot;<br><br>msg = MIMEText(&quot;This is a test email from Python via Zoho Canada SMTP.&quot;, &#39;plain&#39;)<br>msg[&#39;Subject&#39;] = &quot;Test from Zoho Canada&quot;<br>msg[&#39;From&#39;] = EMAIL<br>msg[&#39;To&#39;] = &quot;recipient@example.com&quot;<br><br>with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:<br>    server.starttls()<br>    server.login(EMAIL, APP_PASSWORD)<br>    server.send_message(msg)<br><br>print(&quot;✅ Email sent successfully!&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=576a37f09f78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/how-to-send-emails-via-zoho-mail-with-python-smtp-for-free-576a37f09f78">How to Send Emails via Zoho Mail with Python SMTP (for FREE)</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Send and Receive Custom Domain Emails via Gmail (Setup with Zoho + Cloudflare) and it is…]]></title>
            <link>https://medium.com/preprintblog/how-to-send-and-receive-custom-domain-emails-via-gmail-setup-with-zoho-cloudflare-and-it-is-c6a3a41a8196?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6a3a41a8196</guid>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[gmail]]></category>
            <category><![CDATA[domains]]></category>
            <category><![CDATA[zoho]]></category>
            <category><![CDATA[email]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 22:35:56 GMT</pubDate>
            <atom:updated>2025-04-14T22:41:46.590Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Send and Receive Custom Domain Emails via Gmail (Setup with Zoho + Cloudflare) and it is FREE!</h3><p>Let’s say you have a domain like <a href="http://www.henrywu.me/">www.henrywu.me</a><a href="http://www.henrywu.me,/">,</a> and you want to set up an email address such as ask@henrywu.me, using Gmail for both receiving and sending — without spending a penny. This blog will show you exactly how to do that.</p><p>In short, the solution uses <strong>Cloudflare Email Routing</strong> to forward incoming emails to your personal Gmail inbox, and <strong>Zoho Mail</strong> to handle authenticated SMTP sending.</p><p><strong>✨ Overview</strong></p><ul><li><strong>Receive emails</strong> sent to ask@henrywu.me in your Gmail inbox (e.g., henry@gmail.com)</li><li><strong>Reply/send</strong> emails from Gmail as ask@henrywu.me</li><li><strong>Free</strong> solution using Cloudflare Email Routing and Zoho Mail</li></ul><h3>Step-by-Step Setup</h3><h3>1. Register Your Domain</h3><p>Use any registrar (e.g., Godaddy, Namecheap) and point DNS to Cloudflare by updating nameservers.</p><h3>2. Set Up Cloudflare DNS</h3><ul><li>Log in to <a href="https://cloudflare.com/">Cloudflare</a></li><li>Add your domain</li><li>Use <strong>Full DNS setup</strong> and verify control</li></ul><h3>3. Enable Cloudflare Email Routing</h3><ul><li>Go to <strong>Email &gt; Email Routing</strong> in Cloudflare dashboard</li><li>Enable Email Routing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1d3ouSH8Y6caUjoZKD6uAQ.png" /></figure><ul><li>Add a rule:</li></ul><blockquote>Custom address: ask@henrywu.me</blockquote><blockquote>Forward to: your Gmail (e.g., henry@gmail.com)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phMxMTucpDd79kAuL1DJ3Q.png" /></figure><ul><li>Cloudflare will auto-configure <strong>MX records</strong> like:</li></ul><blockquote>route1.mx.cloudflare.net</blockquote><blockquote>route2.mx.cloudflare.net</blockquote><blockquote>route3.mx.cloudflare.net</blockquote><p>Now, all mail to ask@henrywu.me will forward to your Gmail inbox.</p><h3>4. Set Up Zoho Mail for SMTP (Sending)</h3><ul><li>Go to <a href="https://mail.zoho.com/orgsignup.do?plan=mailPremiumTrial">Zoho</a>, and Choose <strong>Mail Free Plan</strong> for custom domains</li><li>Add your domain henrywu.me in <strong>Zoho Mail Admin Console</strong></li><li>Complete DNS verification:</li><li>Add Zoho’s <strong>TXT verification record</strong> in Cloudflare DNS</li><li><strong>DO NOT</strong> use Zoho’s MX records (Cloudflare is handling receiving)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15lop2o5h1sXpBV1WKccxw.png" /></figure><h3>5. Create a Mailbox in Zoho</h3><ul><li>In Zoho Admin Console → Users → Add User</li><li>Email: ask@henrywu.me</li><li>Set password</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oaVNlcqROi6IIDoWaoYEaA.png" /></figure><h3>6. Configure Gmail to Send</h3><ol><li>Open Gmail → <strong>Settings &gt; See All Settings &gt; Accounts and Import</strong></li><li>Under <strong>“Send mail as”</strong>, click <strong>Add another email address</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNX3DnfNSMSqukfX972Mgw.png" /></figure><p>Fill:</p><ul><li>Name: Your Name or Brand</li><li>Email: ask@henrywu.me</li><li>Uncheck “Treat as alias” (optional)</li></ul><p>SMTP settings:</p><ul><li>SMTP Server: smtp.zoho.com (Zoho Global ) or smtp.zohocloud.ca <em>(Zoho Canada)</em></li><li>Port: 587 (TLS)</li><li>Username: ask@henrywu.me</li><li>Password: your Zoho mailbox password</li></ul><p>Gmail sends a verification email</p><ul><li>You’ll receive it in Gmail inbox via Cloudflare routing</li><li>Click the link to verify</li></ul><h3>🌐 Result</h3><ul><li>✅ Email to ask@henrywu.me arrives in your Gmail inbox</li><li>✅ You can reply and send emails <strong>as </strong>ask@henrywu.me directly in Gmail</li><li>✅ All of this is <strong>free</strong>, with professional deliverability using SPF/DKIM/DMARC</li></ul><h3>🚀 Bonus: Add More Emails</h3><ul><li>Add another forwarding rule in Cloudflare</li><li>Add another mailbox in Zoho (free plan supports 5)</li><li>Repeat Gmail “Send mail as” setup for the new address</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_64_hnKERPVzlcwHQpFRg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6a3a41a8196" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/how-to-send-and-receive-custom-domain-emails-via-gmail-setup-with-zoho-cloudflare-and-it-is-c6a3a41a8196">How to Send and Receive Custom Domain Emails via Gmail (Setup with Zoho + Cloudflare) and it is…</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【11/n】Installing Redis6 on Amazon Linux 2023 EC2: A Step-by-Step Guide]]></title>
            <link>https://medium.com/preprintblog/11-n-installing-redis6-on-amazon-linux-2023-ec2-a-step-by-step-guide-e6f7dec7e932?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6f7dec7e932</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 03:05:09 GMT</pubDate>
            <atom:updated>2024-12-20T03:05:09.718Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide will walk you through the process of installing and configuring Redis 6 on an Amazon Linux 2023 EC2 instance. Redis is an open-source, in-memory data structure store that can be used as a database, cache, message broker, and queue.</p><h3>Prerequisites</h3><ul><li>An EC2 instance running Amazon Linux 2023</li><li>SSH access to your EC2 instance</li><li>Appropriate permissions to install packages and modify system configurations</li></ul><h3>Installation Steps</h3><h3>1. Update Your System</h3><p>First, ensure your system packages are up to date:</p><pre>sudo yum update</pre><h3>2. Install Redis 6</h3><p>On Amazon Linux 2023, Redis 6 can be installed directly using the dnf package manager:</p><pre>sudo dnf install redis6</pre><h3>3. Start and Enable Redis Service</h3><p>After installation, start the Redis service and enable it to start automatically on boot:</p><pre># Start Redis service<br>sudo systemctl start redis6<br><br># Enable Redis to auto-start on boot<br>sudo systemctl enable redis6<br><br># Verify Redis status<br>sudo systemctl status redis6</pre><h3>4. Verify Installation</h3><p>Test if Redis is working correctly using the Redis CLI:</p><pre>redis6-cli ping</pre><p>If you receive PONG as a response, Redis is working correctly.</p><h3>Configuration for Remote Access (Development Only)</h3><h3>1. Edit Redis Configuration</h3><p>Open the Redis configuration file:</p><pre>sudo nano /etc/redis6/redis6.conf</pre><p>it should looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8KgebjLxEAj3x_KNJUVlg.png" /></figure><p>Add or modify these key settings:</p><pre># Network configuration<br>bind 0.0.0.0        # Allow connections from any IP<br>protected-mode no   # Disable protected mode<br>port 6379          # Default Redis port<br><br># Other important settings<br>timeout 0<br>tcp-keepalive 300<br>daemonize no       # Using systemd<br>supervised auto</pre><h3>2. Restart Redis</h3><p>After making configuration changes, restart Redis:</p><pre>sudo systemctl restart redis6</pre><h3>3. Configure Security Group</h3><p>For remote access, you need to configure your EC2’s security group:</p><ol><li>Go to AWS Console → EC2 → Security Groups</li><li>Select your EC2’s security group</li><li>Add an inbound rule:</li></ol><ul><li>Type: Custom TCP</li><li>Port: 6379</li><li>Source: Your IP address (for security)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4M0mOgUrSj47RdsuuGdlhw.png" /></figure><p><strong>Security Note:</strong> Opening Redis to remote connections should only be done in development environments. For production, consider using:</p><ul><li>Redis password authentication</li><li>VPN or SSH tunneling</li><li>Private networking between instances</li><li>AWS ElastiCache for production workloads</li></ul><h3>Testing Remote Connection</h3><p>You can test the connection from your local machine using Python:</p><pre>import redis<br><br># Replace YOUR_EC2_PUBLIC_IP with your EC2&#39;s public IP<br>redis_url = &#39;redis://YOUR_EC2_PUBLIC_IP:6379&#39;<br><br>try:<br>    r = redis.from_url(https://medium.com/redis_url)<br>    r.ping()<br>    print(&quot;Successfully connected to Redis&quot;)<br>except redis.ConnectionError as e:<br>    print(f&quot;Could not connect to Redis: {e}&quot;)</pre><h3>Common Issues and Solutions</h3><ol><li><strong>Command Not Found</strong>: If redis-cli command is not found, use redis6-cli instead, as this is the correct command name in Amazon Linux 2023.</li><li><strong>Connection Refused</strong>: If you get a “Connection refused” error when trying to connect remotely:</li></ol><ul><li>Verify Redis is running: sudo systemctl status redis6</li><li>Check if Redis is listening on all interfaces: ss -an | grep 6379</li><li>Verify security group settings</li><li>Ensure the Redis configuration file has the correct bind settings</li></ul><h3>Best Practices for Production</h3><ol><li><strong>Security</strong>:</li></ol><ul><li>Never expose Redis directly to the internet</li><li>Use strong passwords if authentication is enabled</li><li>Regularly update Redis to the latest stable version</li><li>Use AWS security groups to restrict access</li></ul><ol><li><strong>Monitoring</strong>:</li></ol><ul><li>Monitor Redis memory usage</li><li>Set up alerts for connection issues</li><li>Keep track of Redis log files</li></ul><h3>Conclusion</h3><p>You now have Redis 6 running on your Amazon Linux 2023 EC2 instance. For production environments, consider using AWS ElastiCache for Redis, which provides a fully managed solution with enhanced security and scalability features.</p><p>Remember to always follow security best practices when deploying Redis in any environment, especially when allowing remote connections.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f7dec7e932" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/11-n-installing-redis6-on-amazon-linux-2023-ec2-a-step-by-step-guide-e6f7dec7e932">【11/n】Installing Redis6 on Amazon Linux 2023 EC2: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【10/n】Building a Production-Ready Logging System for Flask Applications]]></title>
            <link>https://medium.com/preprintblog/10-n-building-a-production-ready-logging-system-for-flask-applications-0c09c4f6e5bd?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c09c4f6e5bd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 06:40:13 GMT</pubDate>
            <atom:updated>2024-12-19T06:40:13.651Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we’ll walk through creating a sophisticated logging system for Flask applications that’s suitable for production environments. We’ll implement a date-based directory structure, automatic log rotation, timezone handling, and log retention policies.</p><h3>The Challenge</h3><p>When building production Flask applications, proper logging is crucial for monitoring, debugging, and maintaining application health. However, a basic logging setup often falls short in addressing several key requirements:</p><ol><li>Organized log storage with a clear directory structure</li><li>Proper timezone handling for accurate timestamps</li><li>Log rotation to manage file sizes</li><li>Automatic cleanup of old logs to manage disk space</li><li>Different logging paths for development and production environments</li></ol><h3>The Solution</h3><p>We’ll build a comprehensive logging system that addresses these challenges with the following features:</p><ul><li>Directory structure: log/YYYYMM/YYYYMMDD.log</li><li>6-month log retention policy</li><li>Vancouver timezone support</li><li>Environment-aware configuration</li><li>Automatic directory creation and cleanup</li></ul><h3>Prerequisites</h3><p>First, ensure you have the required dependencies:</p><pre>pip install Flask pytz</pre><h3>Project Structure</h3><p>Here’s how our Flask application is structured:</p><pre>my_flask_app/<br>├── app/<br>│   ├── __init__.py<br>│   ├── config.py<br>│   └── utils/<br>│       └── logging.py<br>├── log/<br>│   └── YYYYMM/<br>│       └── YYYYMMDD.log<br>└── requirements.txt</pre><h3>Implementation Details</h3><h3>1. Creating the Logging Setup Function</h3><p>Let’s start with our logging configuration in app/utils/logging.py:</p><pre>import os<br>import sys<br>import logging<br>import shutil<br>from datetime import datetime, timedelta<br>import pytz<br>from logging.handlers import TimedRotatingFileHandler<br>from pathlib import Path<br><br>def setup_logging(app):<br>    &quot;&quot;&quot;<br>    Configure logging for the Flask application with date-based directory structure<br>    and retention policy using Vancouver timezone.<br>    &quot;&quot;&quot;<br>    # Create formatter with Vancouver timezone<br>    vancouver_tz = pytz.timezone(&#39;America/Vancouver&#39;)<br>    <br>    class VancouverFormatter(logging.Formatter):<br>        def converter(self, timestamp):<br>            dt = datetime.fromtimestamp(timestamp)<br>            return vancouver_tz.localize(dt)<br>        <br>        def formatTime(self, record, datefmt=None):<br>            dt = self.converter(record.created)<br>            if datefmt:<br>                return dt.strftime(datefmt)<br>            return dt.strftime(&#39;%Y-%m-%d %H:%M:%S %Z&#39;)<br><br>    formatter = VancouverFormatter(<br>        &#39;[%(asctime)s] %(levelname)s in %(module)s: %(message)s&#39;<br>    )</pre><h3>2. Setting Up the Directory Structure</h3><p>The logging system creates a hierarchical directory structure based on dates:</p><pre># Determine base log path based on environment<br>    if app.config[&#39;FLASK_ENV&#39;] == &#39;development&#39;:<br>        base_log_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), &#39;log&#39;)<br>    else:<br>        base_log_path = &#39;/var/www/log&#39;<br><br>    # Get current date in Vancouver timezone<br>    current_date = datetime.now(vancouver_tz)<br>    <br>    # Create YYYYMM folder structure<br>    month_folder = current_date.strftime(&#39;%Y%m&#39;)<br>    log_dir = os.path.join(base_log_path, month_folder)<br>    os.makedirs(log_dir, exist_ok=True)</pre><h3>3. Implementing Log Cleanup</h3><p>To manage disk space, we implement automatic cleanup of old logs:</p><pre>def cleanup_old_logs(base_log_path, timezone):<br>    &quot;&quot;&quot;<br>    Clean up log directories older than 6 months.<br>    &quot;&quot;&quot;<br>    try:<br>        current_date = datetime.now(timezone)<br>        cutoff_date = current_date - timedelta(days=180)  # 6 months<br>        <br>        for dir_name in os.listdir(base_log_path):<br>            try:<br>                dir_date = datetime.strptime(dir_name, &#39;%Y%m&#39;)<br>                dir_date = timezone.localize(dir_date)<br>                <br>                if dir_date &lt; cutoff_date:<br>                    dir_path = os.path.join(base_log_path, dir_name)<br>                    shutil.rmtree(dir_path)<br>                    print(f&quot;Removed old log directory: {dir_path}&quot;)<br>            except (ValueError, OSError) as e:<br>                print(f&quot;Error processing directory {dir_name}: {str(e)}&quot;)<br>                continue<br>    except Exception as e:<br>        print(f&quot;Error during cleanup: {str(e)}&quot;)</pre><h3>4. Integration with Flask Application</h3><p>In your Flask application’s __init__.py, integrate the logging setup:</p><pre>from flask import Flask<br>from .utils.logging import setup_logging<br><br>def create_app():<br>    app = Flask(__name__)<br>    <br>    # Get the appropriate config for current environment<br>    config_class = get_config()<br>    app.config.from_object(config_class)<br>    <br>    # Set up logging<br>    setup_logging(app)<br>    <br>    # Rest of your app initialization...<br>    return app</pre><h3>Understanding Flask Logger Usage: app.logger vs current_app.logger</h3><p>When logging in Flask applications, you’ll encounter two common patterns: app.logger and current_app.logger. Let&#39;s understand when to use each:</p><h3>1. app.logger</h3><pre>@app.route(&#39;/example&#39;)<br>def example_route():<br>    app.logger.info(&#39;Processing example route&#39;)<br>    return &#39;Done&#39;</pre><p>Use app.logger when:</p><ul><li>You’re in the main application file where app is directly available</li><li>Inside route decorators where app is in scope</li><li>In functions where the Flask app instance is passed as a parameter</li><li>During application initialization or configuration</li></ul><h3>2. current_app.logger</h3><pre>from flask import current_app<br><br>def user_signup(email):<br>    current_app.logger.info(f&quot;Signup attempt for email: {email}&quot;)<br>    # Process signup</pre><p>Use current_app.logger when:</p><ul><li>Working in blueprint files</li><li>In utility functions or modules where app isn&#39;t directly accessible</li><li>Inside factory pattern implementations</li><li>In any context where you don’t have direct access to the app instance</li><li>When working with Flask’s application context</li></ul><h3>Example Implementation</h3><p>Here’s a practical example showing both usage patterns:</p><pre>from flask import Flask, current_app<br>from flask import Blueprint<br><br># Main app file<br>app = Flask(__name__)<br><br>@app.route(&#39;/main&#39;)<br>def main_route():<br>    # Direct app access<br>    app.logger.info(&#39;Main route accessed&#39;)<br>    return &#39;Main route&#39;<br><br># Blueprint file<br>auth_bp = Blueprint(&#39;auth&#39;, __name__)<br><br>@auth_bp.route(&#39;/signup&#39;)<br>def signup():<br>    # Using current_app because we&#39;re in a blueprint<br>    current_app.logger.info(&#39;Signup route accessed&#39;)<br>    process_signup()<br>    return &#39;Signup&#39;<br><br># Utility function<br>def process_signup():<br>    # Using current_app because we&#39;re in a utility function<br>    current_app.logger.debug(&#39;Processing signup&#39;)</pre><h3>Best Practices</h3><ol><li><strong>Consistency in Modules</strong>:</li></ol><ul><li>Use current_app.logger consistently in blueprints and utility modules</li><li>Use app.logger in your main application file</li></ul><ol><li><strong>Error Handling</strong>:</li></ol><pre>def sensitive_operation():<br>    try:<br>        # Operation code<br>        current_app.logger.info(&#39;Operation successful&#39;)<br>    except Exception as e:<br>        current_app.logger.error(f&#39;Operation failed: {str(e)}&#39;)<br>        raise</pre><p><strong>Context-Aware Logging</strong>:</p><pre>def background_task():<br>    with app.app_context():<br>        current_app.logger.info(&#39;Background task started&#39;)<br>        # Task code</pre><h3>Benefits and Features</h3><ol><li><strong>Organized Log Files</strong>: Logs are automatically organized by year and month, making it easy to locate specific logs.</li><li><strong>Timezone Awareness</strong>: All log entries use Vancouver timezone, ensuring consistent timestamps.</li><li><strong>Automatic Cleanup</strong>: Old logs are automatically removed after 6 months, preventing disk space issues.</li><li><strong>Environment Awareness</strong>: Different log paths for development and production environments.</li><li><strong>Robust Error Handling</strong>: The system includes comprehensive error handling for file operations.</li></ol><h3>Best Practices and Considerations</h3><ol><li><strong>Log Rotation</strong>: Consider implementing log rotation if daily files grow too large.</li><li><strong>Backup Strategy</strong>: Implement a backup strategy for critical logs.</li><li><strong>Monitoring</strong>: Set up monitoring for log directory size and cleanup success.</li><li><strong>Security</strong>: Ensure proper file permissions on log directories.</li><li><strong>Performance</strong>: Monitor logging impact on application performance.</li></ol><h3>Conclusion</h3><p>This logging system provides a robust foundation for Flask applications, offering organized log storage, automatic cleanup, and proper timezone handling. It’s designed to be maintainable and scalable, making it suitable for both development and production environments.</p><p>Remember to adapt the configuration based on your specific needs, such as adjusting the retention period or modifying the log format. You might also want to add additional features like log compression or integration with log aggregation services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c09c4f6e5bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/10-n-building-a-production-ready-logging-system-for-flask-applications-0c09c4f6e5bd">【10/n】Building a Production-Ready Logging System for Flask Applications</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【9/n】Creating a Robust Config.py System in Flask]]></title>
            <link>https://medium.com/preprintblog/9-n-creating-a-robust-config-py-system-in-flask-088c60bf6700?source=rss-e0ad32ea0f20------2</link>
            <guid isPermaLink="false">https://medium.com/p/088c60bf6700</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[config]]></category>
            <dc:creator><![CDATA[Henry Wu]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 04:26:54 GMT</pubDate>
            <atom:updated>2024-12-19T04:26:54.781Z</atom:updated>
            <content:encoded><![CDATA[<p>Flask applications often need different configurations for various environments like development, testing, and production. In this guide, we’ll explore how to create a flexible and maintainable configuration system for your Flask application.</p><h3>Why Good Configuration Matters</h3><p>A well-designed configuration system is crucial because it:</p><ul><li>Separates configuration from code</li><li>Makes environment-specific settings easy to manage</li><li>Keeps sensitive data secure</li><li>Provides flexibility for different deployment environments</li></ul><h3>Setting Up the Configuration Structure</h3><p>Let’s create a config.py file in our Flask application that implements a hierarchical configuration system using Python classes. We&#39;ll use environment variables for sensitive data and provide sensible defaults where appropriate.</p><h3>Base Configuration Class</h3><p>First, we’ll create a base configuration class that contains common settings shared across all environments:</p><pre>from dotenv import load_dotenv<br><br>class BaseConfig:<br>    &quot;&quot;&quot;Base configuration class with common settings&quot;&quot;&quot;<br>    <br>    # Environment settings<br>    FLASK_ENV = os.getenv(&#39;FLASK_ENV&#39;, &#39;development&#39;)<br>    SECRET_KEY = os.getenv(&#39;SECRET_KEY&#39;, &#39;default_secret_key&#39;)<br>    <br>    # Flask debug toolbar settings<br>    DEBUG_TB_INTERCEPT_REDIRECTS = False<br>    <br>    # SQLAlchemy settings<br>    SQLALCHEMY_TRACK_MODIFICATIONS = False<br>    <br>    # API settings<br>    DEBUG = False<br>    API_TIMEOUT = 30<br>    API_RETRIES = 3<br>    <br>    # Caching configuration<br>    CACHE_TYPE = &quot;simple&quot;<br>    CACHE_DEFAULT_TIMEOUT = 300</pre><h3>Environment-Specific Configurations</h3><p>Next, we’ll create environment-specific classes that inherit from the base class:</p><pre>class DevelopmentConfig(BaseConfig):<br>    &quot;&quot;&quot;Development environment specific configuration&quot;&quot;&quot;<br>    DEBUG = True<br><br>class ProductionConfig(BaseConfig):<br>    &quot;&quot;&quot;Production environment specific configuration&quot;&quot;&quot;<br>    CACHE_TYPE = &quot;redis&quot;<br>    RDS_DB_HOST = os.getenv(&quot;RDS_DB_HOST&quot;, &quot;production-db-host&quot;)</pre><h3>Configuration Factory Function</h3><p>Finally, we’ll create a factory function to return the appropriate configuration based on the environment:</p><pre>def get_config(env: str = None) -&gt; Any:<br>    &quot;&quot;&quot;<br>    Factory function to get the appropriate config based on environment<br>    <br>    Args:<br>        env: Environment name (&#39;development&#39;, &#39;production&#39;, &#39;testing&#39;)<br>    <br>    Returns:<br>        Config class for the specified environment<br>    &quot;&quot;&quot;<br>    configs = {<br>        &#39;development&#39;: DevelopmentConfig,<br>        &#39;production&#39;: ProductionConfig<br>    }<br>    <br>    # Get environment from param, env var, or default to development<br>    environment = env or os.getenv(&#39;FLASK_ENV&#39;, &#39;development&#39;)<br>    return configs.get(environment, DevelopmentConfig)</pre><h3>Uppercase Configuration Names</h3><p>Flask follows a specific convention where all configuration variables should be uppercase. This is not just a style choice — it’s a requirement for Flask to properly recognize and load these variables.</p><pre>class BaseConfig:<br>    # Correct - uppercase configuration names<br>    DEBUG = False<br>    SECRET_KEY = os.getenv(&#39;SECRET_KEY&#39;, &#39;default_secret_key&#39;)<br>    SQLALCHEMY_TRACK_MODIFICATIONS = False<br>    <br>    # Incorrect - lowercase names won&#39;t be recognized by Flask<br>    debug = False                  # Won&#39;t work<br>    secret_key = &#39;some_secret&#39;    # Won&#39;t work</pre><p>Why uppercase?</p><ul><li>Flask specifically looks for uppercase variables when loading configuration</li><li>It helps distinguish configuration variables from regular class attributes</li><li>It’s a Python convention for constants</li><li>It makes configuration variables easily identifiable in the code</li></ul><p>Common patterns for naming:</p><ul><li>Use uppercase for all letters</li><li>Use underscores to separate words</li><li>Prefix related configurations with a common term:</li></ul><pre># Database-related configurations<br>DATABASE_HOST = &#39;localhost&#39;<br>DATABASE_PORT = 5432<br>DATABASE_NAME = &#39;myapp&#39;<br><br># API-related configurations<br>API_TIMEOUT = 30<br>API_VERSION = &#39;v1&#39;<br>API_BASE_URL = &#39;https://api.example.com&#39;</pre><h3>Best Practices and Tips</h3><ol><li><strong>Use Environment Variables</strong></li></ol><ul><li>Store sensitive information like API keys and database credentials in environment variables</li><li>Use .env files for local development</li><li>Never commit .env files to version control</li></ul><ol><li><strong>Provide Default Values</strong></li></ol><ul><li>Always include default values for non-sensitive configuration</li><li>Use os.getenv() with a default value for environment variables</li></ul><p><strong>Type Hints</strong></p><ul><li>Use type hints to make the code more maintainable and catch potential errors</li></ul><pre>def get_config(env: str = None) -&gt; Any:</pre><p><strong>Documentation</strong></p><ul><li>Add docstrings to classes and functions</li><li>Comment on non-obvious configuration values</li><li>Keep a README with setup instructions</li></ul><h3>Using the Configuration</h3><p>To use this configuration in your Flask application:</p><p>in __init__.py file:</p><pre>from .config import get_config<br><br>def create_app():<br>    app = Flask(__name__)<br>    <br>    # Get the appropriate config for current environment<br>    config_class = get_config()<br>    app.config.from_object(config_class)</pre><p>in python file:</p><pre>from flask import current_app<br><br>FLASK_ENV = current_app.config[&#39;FLASK_ENV&#39;]</pre><h3>Conclusion</h3><p>A well-structured configuration system is essential for maintaining a Flask application across different environments. By following these patterns, you can create a flexible, secure, and maintainable configuration that grows with your application.</p><p>Remember to:</p><ul><li>Keep sensitive data in environment variables</li><li>Use inheritance to avoid duplicating common settings</li><li>Provide sensible defaults</li><li>Document your configuration options</li><li>Use type hints for better code maintenance</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=088c60bf6700" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preprintblog/9-n-creating-a-robust-config-py-system-in-flask-088c60bf6700">【9/n】Creating a Robust Config.py System in Flask</a> was originally published in <a href="https://medium.com/preprintblog">preprintblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>