<?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 Hoppa Digital on Medium]]></title>
        <description><![CDATA[Stories by Hoppa Digital on Medium]]></description>
        <link>https://medium.com/@hoppa-digital?source=rss-eec8759fb141------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6UGriR6RD1HbsLsQuH9xhA.png</url>
            <title>Stories by Hoppa Digital on Medium</title>
            <link>https://medium.com/@hoppa-digital?source=rss-eec8759fb141------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:37:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hoppa-digital/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[What  I Learned from Developing a Google Doc Add-on in Two Weeks]]></title>
            <link>https://medium.com/bitsrc/what-i-learned-from-developing-a-google-doc-add-on-in-two-weeks-5985675aff81?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/5985675aff81</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-docs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 19:17:21 GMT</pubDate>
            <atom:updated>2025-03-05T12:06:31.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>What I Learned from Developing a Google Docs Add-on in Two Weeks</h3><h4>Tips and hard-learned lessons</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e-kdRz-zu_w2H25R" /><figcaption>Photo by <a href="https://unsplash.com/@einarr05?utm_source=medium&amp;utm_medium=referral">Einar H. Reynis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5b8R_GgBiZhF_r62XybHA.jpeg" /></figure><p>We developed and published <a href="https://gsuite.google.com/u/1/marketplace/app/referencer/161289460786">an open-sourced Google Doc Add-on named <strong>Referencer</strong></a> that helps automate cross-reference for figures, tables, and section titles in about two weeks.</p><p>I learned something new from this short but fun experience, and want to share with others who are interested in building add-ons for GSuite products and tools (e.g., Google Docs and Sheets).</p><figure><a href="https://bit.cloud/"><img alt="Build in AI speed — Compose enterprise-grade applications, features, and components" src="https://cdn-images-1.medium.com/max/1024/1*yX0vq3scSudyT61IuWFuEg.png" /></a><figcaption>Build in AI speed — Compose enterprise-grade applications, features, and components</figcaption></figure><h3>Motivation</h3><p>I do a lot of writing, individually or collaboratively, as a part of <a href="https://cse.wwu.edu/computer-science/qiangh">my job</a>. On the one hand, I like how Latex automates things, but I hate the writing experience in most Latex-based tools. <a href="https://www.overleaf.com/">Overleaf</a> makes collaborative writing in Latex easier, but I still find its user experience less than ideal.</p><p>On the other hand, I enjoy the writing experience in Google Docs very much, but I hate to manually adjust things in Google Docs that can be easily automated in Latex, such as cross-reference and citations. As a result, I want to keep enjoying my writing experience in Google Docs, but automate certain things like I would do when using Latex. I tried every existing add-on that helps with cross-reference on the GSuite Market — they either achieved a piece that’s too tiny (e.g., cross-reference for only section titles) or are less intuitive than expected (e.g., no clue of how to use it after minutes of reading).</p><p>When everything moved online due to pandemic since this March, I couldn’t help students in my research lab as I used to. Several of our research projects were nearly halted. Therefore, I decided to do something else with two of my students, in the hope that it can help them grow as well as benefit others — <strong>developing an intuitive Google Doc add-on that achieves the automation of cross-reference</strong>.</p><h3>Planning and Design</h3><p>We don’t have a month or two to work on this — I have classes to teach, papers to write, and painful service work to do; my research students have a set of online courses to take and probably more to handle than what I have on my plate. We gave us about two weeks to finish this task, so careful planning is the key to our success. Here was the plan that I made:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEe0YOs_fxcPMesrwDfjEA.png" /><figcaption>Fig. 1. A two-week plan with five sprints</figcaption></figure><p>Here are three key lessons that I learned from our first sprint of learning JS/Google App Script/Google Doc API:</p><p><strong>1. Learning Javascript (JS) in 3 days is doable (to some extent)</strong>. JS is needed to develop add-ons for Google Docs. I never got a chance to dive very deep into JS before, and my 3-day learning experience says that it is possible to pick JS up in 3 days to reach a level that is sufficient for you to handle a small project like this one. Here is the strategy I used to make my 3-day learning as effective as possible:</p><ul><li><em>Picking up JS syntax using </em><a href="https://www.codecademy.com/learn/introduction-to-javascript"><em>Code Academy</em></a>: I like how Code Academy makes the learning of syntax interactive. I didn’t go through their tutorial step by step — Instead, I read the instruction and often jump to read their solutions as <a href="https://en.wikipedia.org/wiki/Worked-example_effect">worked-out examples</a>. I didn’t pay for the subscription of Code Academy, so I didn’t have access to their problem-solving tutorials — I don’t think they are necessary to achieve my goal at all.</li><li><em>Flex problem-solving muscles using </em><a href="https://leetcode.com/"><em>leetcode</em></a>: I practiced about five to seven problem-solving using JS on an online judge tool, leetcode, on some of the selected topics, such as stack, hashtable, and backtracking. This is not to prepare for interviews :) I like how leetcode provides an interactive online judge tool for solving some well-known problems. You may think this is not necessary — I agree, but they helped me practice the syntax that I learned, and make the learning of syntax less boring.</li><li><em>Solve some simple problems in the context</em>: I solved a set of simple problems in the context of interacting with a Google Doc through its API, such as collecting all paragraphs and print them out individually, and collecting all bookmarks. The hardest problem that I had myself solved was to collect all links, including the texts and the URLs, which turned out to be very useful for this project — <a href="https://github.com/Citasion/referencer/blob/633121f47e133018b2f46ec65709f7c5f2ec6b60/bookmark.gs#L157">We need to collect all link objects that are associated with bookmarks, which is best solved by recursion</a>.</li></ul><p><strong>2. The </strong><a href="https://developers.google.com/apps-script/guides/docs#structure_of_a_document"><strong>structure of a Google Doc</strong></a><strong> should be seen as a Document Object Model (DOM)</strong>. The understanding of <a href="https://www.w3.org/TR/DOM-Level-2-Core/introduction.html">DOM</a> is critical for interacting with Google Docs through its API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JiAE8sOzglyHLCU2KLxVQ.png" /><figcaption>A simplified visualization of a Google Doc.</figcaption></figure><p>For instance, you can easily add a few more paragraphs to a Google Doc:</p><pre>var body = DocumentApp.getActiveDocument().getBody();<br>body.appendParagraph(&#39;Paragraph 1&#39;);<br>body.appendParagraph(&#39;Paragraph 2&#39;);<br>body.appendParagraph(&#39;Paragraph 3&#39;);<br>body.getParagraphs(); // return a list of Paragraph objects</pre><p>The <a href="https://developers.google.com/apps-script/reference/document/body">document body is a well-defined class</a> with a set of handy methods. The .getParagraphs() is one of these methods, and it returns a list of <a href="https://developers.google.com/apps-script/reference/document/paragraph">Paragraph</a> objects.</p><p><strong>3. Be prepared for a rough debugging experience in </strong><a href="https://developers.google.com/apps-script"><strong>Google App Script</strong></a><strong> (GAS)</strong>. GAS is a scripting platform for developing light-weight applications such as add-ons for Google Docs or Sheets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*BqF5bhZ4TUvzK9Z_95HJHw.png" /><figcaption>GAS Environment.</figcaption></figure><p>If you are experienced in web development, you may rely more on Chrome or Firefox DevTools, various breakpoints, and code tracing, but less on using console.log() to print stuff out during testing and debugging.</p><p>When you are working on an add-on for Google Docs, I find it difficult to leave the online environment of GAS to code locally, as I need GAS for testing and debugging. In the environment of GAS, Chrome or Firefox DevTools help very little. Although you can still do one or two types of breakpoints in GAS, you need to use Logger.log() to print stuff out a lot for testing and debugging (<em>Note: </em><em>Logger.log() is the equivalent of </em><em>console.log() for GAS</em>). I tried to set up a local programming environment for GAS using <a href="https://github.com/google/clasp">CLASP</a>, but eventually gave up — If getting fluent in the tool takes too long, it is no longer a worthy investment for me in the context of this project.</p><h3>Research existing products and user behaviors</h3><p>We studied how existing Google Doc add-ons achieve cross-reference, as well as how regular writers write in Google Docs. If you never heard of the term “cross-reference” before, here is its definition:</p><blockquote>An instance within a document which refers to related information elsewhere in the same document.</blockquote><p>When it comes to a Google Doc, this is what we want to achieve:</p><ul><li>auto-number figures, tables, and section titles</li><li>synch cross-reference of any figures, tables, and section titles</li></ul><p>Here is the one key lesson that I learned from our second sprint of research and design:</p><p><strong>Easy approaches to achieve the aimed functionality may not bring the best user experience</strong>. In the context of this project, an easy way to achieve auto-numbering and synchronization of cross-reference is to utilize URLs — insert a URL for each figure/table/section title (e.g., #gray-cat), and insert a corresponding link on the reference to that URL). This approach is technically easy to achieve in terms of programming, and is utilized by the existing cross-reference add-ons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*ZoH32hnFLW3qd42W2getvA.png" /><figcaption>An illustration of this approach from <a href="https://gsuite.google.com/u/1/marketplace/app/cross_reference/269114033347">Cross Reference Add-on</a>.</figcaption></figure><p>By going through the comments of the existing add-ons and asking other writers who often write in Google Docs, we found the bottleneck of this approach is the manual insertion of URLs that start with #, and linking them in referenced texts. This approach is strange to less tech-savvy users. Plus, if there are many figures or tables in a single document, this can become quite tedious. Synthesizing the information and feedback, we decide not to adopt this approach, despite that it is easy to achieve in terms of programming.</p><p>In a separate effort to study the APIs and built-in functions of Google Docs, we found that:</p><ul><li>Section titles can be cast as headings with consistent styles, which is a recommended practice by Google Docs.</li><li>Bookmarks are easy to add and link to from anywhere in the same Google Doc.</li></ul><p>Building on top of these two built-in functions, we can bypass the bottleneck of relying on URLs only and provide a better user experience for cross-reference — there is no need to insert a set of bizarre URLs for figures/tables/section titles. Plus, adding a link to a Bookmark is built to be friendly by Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*YaAR37M_haOA7Io8BBAngw.jpeg" /><figcaption>A demonstration of referencing a Bookmark from <a href="https://gsuite.google.com/u/1/marketplace/app/referencer/161289460786">Referencer</a>.</figcaption></figure><p>PS: <em>We didn’t realize that this is substantially more difficult to achieve through programming until we started our implementation — this is covered in the next section.</em></p><h3>Implementation and testing</h3><p>We code intensively for about a week, wrapping up the implementation and testing in time. Here are the two key lessons that I learned from our sprint of implementation and testing:</p><p><strong>1. Set the code structure to meet the publication expectation from the start</strong>. The structure of a GSuite add-on can be generalized and illustrated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6luJyCqW5a_w9jOYyO2Wgw.png" /></figure><p>Every GSuite add-on requires a <a href="https://developers.google.com/gsuite/add-ons/concepts/gsuite-manifests">manifest</a> appscript.json, which contains certain details about the script and its operation, such as OAuth scope and add-on name. The rest gs files listed in the above figure are not required, but used as a part of a general structure of many open-sourced GSuite add-ons:</p><ul><li>The main file handles the interactions between a user and your add-on. The main file calls functions defined in the error-handler file to handle errors, and in other gs files to help with interactions.</li><li>The error-handler defines all possible responses for user behaviors that may lead to errors in executing the code of your add-on.</li><li>You may see a lot of add-ons have a “Help” button that leads to a prompt with links and a brief intro — Don’t waste your time to configure the UIs for it, as it is taken care of automatically during the publication process. There is no clear instruction on how this “Help” button is generated in the manual, and we wasted some time dealing with it until we found out what it was about:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*VBKOTRh2qQ2kLrpe_xIeug.png" /><figcaption>A sample Help prompt from <a href="https://gsuite.google.com/u/1/marketplace/app/referencer/161289460786">Referencer</a>.</figcaption></figure><p><strong>2. You will often need to build custom classes on top of the classes defined in Google API.</strong> In the context of this project, we need to collect all bookmarks in a Google Doc — <a href="https://developers.google.com/apps-script/reference/document/document#getbookmarks">you can collect all bookmarks as a list using Google Docs API</a>, but these bookmarks are not put into the list by order of their appearance in a document, which is not explained at all in the API manual. During testing, we also discovered that we have to insert a batch of new bookmarks to replace the old ones inserted by users to achieve auto-numbering and text updates. Otherwise, all kinds of weird bugs would fly around. Here is our final design for a new Bookmark class named <a href="https://github.com/Citasion/referencer/blob/633121f47e133018b2f46ec65709f7c5f2ec6b60/bookmark.gs#L65">BookmarkObj</a> to handle all possible cross-reference updates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*NAJTgpFpW5YPif7iP____Q.png" /></figure><h3>Publishing on GSuite Market</h3><p>Overall, I learned the most from the sprint of publishing this application on the GSuite Market — I was unfamiliar with the process, and I don’t feel that the process is explained as clearly as it could be in the manual. Here are three key lessons that I learned:</p><p><strong>1. Deal with the logistics as early as you can.</strong> The publication requires a set of assets (e.g., logos and screenshots) and a website with necessary information (e.g., privacy policy and terms of service). <a href="https://support.google.com/a/topic/1409901?authuser=0">Moreover, the website domain needs to be verified</a>. All these works can be done in a parallel thread if you are working in a team of two or more people. Even if you are working alone, it is helpful to think about these tasks early.</p><p><strong>2. Submit </strong><a href="https://support.google.com/cloud/answer/6158849?hl=en"><strong>OAuth consent screen</strong></a><strong> for approval as early as you can. </strong>Add-on review for G Suite Marketplace publication is a two-step process. OAuth consent screen review is the first step, which may take a few days or weeks, as well as a few rounds of rejection &amp; request for more information. OAuth consent screen allows users to choose whether they want to grant access to their private data, and give them a link to the terms of service and privacy policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*QUjuM_BVFp3mwrEDwpvDCg.jpeg" /><figcaption>A sample OAuth consent screen from <a href="https://gsuite.google.com/u/1/marketplace/app/referencer/161289460786">Referencer</a>.</figcaption></figure><p>When you are developing an add-on, you certainly won’t need to get to the finishing stage to figure out the <a href="https://developers.google.com/identity/protocols/oauth2/scopes">Scopes for Google APIs</a> your add-on needs. Having the first approval step checked will speed up the whole process.</p><p><strong>3. Deal with as many types of user behaviors as possible, especially those that may lead to errors. </strong>If you fail to deal with those errors, your add-on may be rejected with no feedback at all. A rejection with no explanation and feedback can be frustrating. Our add-on was rejected for one time.</p><p>When dealing with user behaviors that may lead to errors, the last thing you want to do is to send a customized error alert using try &amp; catch — If you do that, it is very likely that your add-on will be rejected for publication. Synthesizing all the information that we could find online, it is best that you stop users from running your add-on code at all and give them a prompt with explanations for any behaviors that may lead to errors. <a href="https://github.com/Citasion/referencer/blob/master/main.gs">You are welcome to check what we did as an example of the approved add-ons</a>.</p><p>Last but not least, Our Add-on can be found at:</p><ul><li>GSuite Market homepage: <a href="https://gsuite.google.com/u/1/marketplace/app/referencer/161289460786">gsuite.google.com/u/1/marketplace/app/referencer/161289460786</a></li><li>User manual: <a href="https://citasion.github.io/referencer/">citasion.github.io/referencer</a></li><li>Open-sourced code: <a href="https://github.com/Citasion/referencer">github.com/Citasion/referencer</a></li></ul><p><strong>If you write in Google Docs, we hope you use </strong><a href="https://gsuite.google.com/u/1/marketplace/app/referencer/161289460786"><strong>our add-on</strong></a><strong> to help automate your cross-references, and </strong><a href="https://github.com/Citasion/referencer/issues/new"><strong>let us know if you find a bug</strong></a><strong>.</strong></p><h3>Related Stories</h3><ul><li><a href="https://blog.bitsrc.io/building-with-react-for-all-platforms-5-top-frameworks-and-tools-affd5baf3de3">Building with React for All Platforms: Top Frameworks and Tools</a></li><li><a href="https://blog.bitsrc.io/code-principles-every-programmer-should-follow-e01bfe976daf">Code Principles Every Programmer Should Follow</a></li><li><a href="https://blog.bitsrc.io/10-super-useful-tricks-for-javascript-developers-f1b76691199b">10 Super Useful Tricks for JavaScript Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5985675aff81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/what-i-learned-from-developing-a-google-doc-add-on-in-two-weeks-5985675aff81">What  I Learned from Developing a Google Doc Add-on in Two Weeks</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</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 Use Flask-WTForms]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/better-programming/how-to-use-flask-wtforms-faab71d5a034?source=rss-eec8759fb141------2"><img src="https://cdn-images-1.medium.com/max/2600/0*rxKmbXL_KkBkq3Vs" width="5616"></a></p><p class="medium-feed-snippet">Make form validation a breeze</p><p class="medium-feed-link"><a href="https://medium.com/better-programming/how-to-use-flask-wtforms-faab71d5a034?source=rss-eec8759fb141------2">Continue reading on Better Programming »</a></p></div>]]></description>
            <link>https://medium.com/better-programming/how-to-use-flask-wtforms-faab71d5a034?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/faab71d5a034</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Tue, 07 Jan 2020 01:42:00 GMT</pubDate>
            <atom:updated>2020-06-20T17:25:05.670Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Build, Test, and Deploy a Flask Application (Part 7)]]></title>
            <link>https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-7-60dde9080330?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/60dde9080330</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Sat, 28 Dec 2019 18:47:58 GMT</pubDate>
            <atom:updated>2021-05-07T20:25:05.820Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deployment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4bu2ZYALhOUJIPXV" /><figcaption>Photo by <a href="https://unsplash.com/@spacex?utm_source=medium&amp;utm_medium=referral">SpaceX</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Meta Information About This Tutorial</h3><h4>Learning goals</h4><ul><li>Deployment</li></ul><p>Note: This tutorial is part of the series <a href="https://medium.com/@neohao/learn-flask-in-a-scientific-way-baf4d8055f6e"><em>Learn Flask in a scientific way</em></a><em>.</em></p><h4>Source code</h4><ul><li>The source code of this tutorial can be accessed on <a href="https://github.com/Neo-Hao/mean-review-collector">GitHub</a>.</li><li>The demo can be accessed on <a href="https://pacific-fortress-91193.herokuapp.com/">this website</a>.</li><li>The version that covers only this tutorial can be accessed <a href="https://github.com/Neo-Hao/mean-review-collector">on GitHub</a>.</li></ul><h3>Plans</h3><p>In this tutorial, we will deploy the web application we have been developing, and show it to the world:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydX83x7tyNIHIQOrCC-Exg.png" /></figure><p>We will be using the free service of <a href="https://www.heroku.com/">Heroku</a>. Heroku is an application hosting service built on top of AWS services such as EC2.</p><p>You can take advantage of the power of EC2 but don’t need to deal with the system administration work that is required by EC2. With Heroku, you can just deploy your application with a git push to their server.</p><h3>Using a Production-Grade WSGI Web Server</h3><p>The Flask development server is not good at handling real requests. To deploy our application, the first thing we need is a production-grade WSGI web server. We will be using <a href="https://gunicorn.org/">gunicorn</a> for this purpose.</p><p>To install gunicorn, type the following line in your terminal (you still need to be in the virtual environment):</p><pre>(env)$ pip install gunicorn==19.9.0</pre><p>As we used the application factory pattern, it is difficult for gunicorn to find our application module directly. As a result, we need to create a file named wsgi.py at the root level:</p><pre>#wsgi.py</pre><pre>from app import create_app<br>app = create_app()</pre><p>To make sure this works, type the following line in your terminal:</p><pre>(env)$ gunicorn wsgi:app</pre><p>You should see the following:</p><pre>[2019-12-27 15:41:08 -0800] [31065] [INFO] Starting gunicorn 19.9.0<br>[2019-12-27 15:41:08 -0800] [31065] [INFO] Listening at: http://127.0.0.1:8000 (31065)<br>[2019-12-27 15:41:08 -0800] [31065] [INFO] Using worker: sync<br>[2019-12-27 15:41:08 -0800] [31068] [INFO] Booting worker with pid: 31068</pre><p>Gunicorn will use your 8000 portal. You should be able to check out your application locally at http://127.0.0.1:8000 through your web browsers.</p><h3>Use Heroku</h3><p>To get ready to deploy your application to Heroku, you will need to:</p><ol><li>Sign up on <a href="https://www.heroku.com/">Heroku.com</a>.</li><li>Install the <a href="https://devcenter.heroku.com/articles/heroku-cli">Heroku CLI</a>. (Follow the instructions on this webpage.)</li><li>Double-check your requirements.txt: Recall that we generated the requirements file in the tutorial <a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21"><em>Build, Test, and Deploy a Flask Application: Part 3 — Application Factory and Blueprints</em></a>. To make sure that we didn’t add any new dependencies (we actually did), run the following line again in your terminal:</li></ol><pre>(env)$ pip freeze &gt; requirements.txt</pre><p>4. Create a new file named procfile:</p><pre>web gunicorn wsgi:app</pre><p>5. Commit and push all the above changes to GitHub.</p><p>Now you are ready for the deployment. Type the following lines in your terminal:</p><pre>(env)$ heroku create<br>(env)$ git push heroku master</pre><p>You can check your live application by running heroku open to open the app in the browser. You can also check my demo on <a href="https://pacific-fortress-91193.herokuapp.com/">this website.</a></p><h3>Tutorial List</h3><ul><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115">Build and test a mini Flask application</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760">Build, Test, and Deploy a Flask Application: Part 1 — Templates</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc">Build, Test, and Deploy a Flask Application: Part 2 — Authentication</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21">Build, Test, and Deploy a Flask Application: Part 3 — Application Factory and Blueprints</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb">Build, Test, and Deploy a Flask Application: Part 4 — Restructuring Testing</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e">Build, Test, and Deploy a Flask Application: Part 5 — Authentication (continued)</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a">Build, Test, and Deploy a Flask Application: Part 6 — Review System</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-7-60dde9080330">Build, Test, and Deploy a Flask Application: Part 7 — Deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60dde9080330" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-7-60dde9080330">Build, Test, and Deploy a Flask Application (Part 7)</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build, Test, and Deploy a Flask Application (Part 6)]]></title>
            <link>https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/952a1b29a02a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Sat, 28 Dec 2019 18:47:33 GMT</pubDate>
            <atom:updated>2021-05-07T20:23:01.417Z</atom:updated>
            <content:encoded><![CDATA[<h4>Review system</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BoddCOt6ZNZ2sPra" /><figcaption>Photo by <a href="https://unsplash.com/@clintadair?utm_source=medium&amp;utm_medium=referral">Clint Adair</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Meta Information About This Tutorial</h3><h4>Learning goals</h4><ul><li>Four basic functions of persistent storage — create, read, update, and delete (CRUD).</li></ul><p>Note: This tutorial is part of the series <a href="https://medium.com/@neohao/learn-flask-in-a-scientific-way-baf4d8055f6e"><em>Learn Flask in a scientific way</em></a><em>.</em></p><h4>Source code</h4><ul><li>The source code of this tutorial can be accessed on <a href="https://github.com/Neo-Hao/mean-review-collector">GitHub</a>.</li><li>The demo can be accessed on <a href="https://pacific-fortress-91193.herokuapp.com/">this website</a>.</li><li>The version that covers only this tutorial can be accessed <a href="https://github.com/Neo-Hao/mean-review-collector">on GitHub</a>.</li></ul><h3>Plans</h3><p>In this tutorial, we will develop and test the review system component of our web application.</p><p>Essentially, this component will allow anyone to view all the mean reviews added by all users, and allow users who registered an account with the application to create, edit, and delete their own reviews.</p><p>The homepage aggregates all reviews from all users and orders them by descending time order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrtPfEbXc4CLswxYkbpAiQ.png" /><figcaption>homepage</figcaption></figure><p>The user dashboard only aggregates reviews from a specific user, and allows the user to create, edit, and delete his or her own reviews:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6aQCrwF7dYeFIi7hlhvtIQ.png" /><figcaption>User dashboard</figcaption></figure><h3>CRUD</h3><p>Our system is meant for users to share the mean reviews they received for their manuscripts, so each user should be able to create, edit, and delete reviews when they log into our application.</p><h4>Create</h4><p>We want users to write a new piece of review on a separate page and store the newly added review to the database, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvaQ_ok2S_HfNVAkpWCiOA.png" /></figure><p>To achieve this, we need to update our database first. We need another table that (1) holds the data of the reviews and (2) links each review to the user who posted it:</p><pre># schema.sql</pre><pre>DROP TABLE IF EXISTS review;<br>CREATE TABLE review (<br>  id INTEGER PRIMARY KEY AUTOINCREMENT,<br>  created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,<br>  author_id INTEGER NOT NULL,<br>  content TEXT NOT NULL,<br>  FOREIGN KEY (author_id) REFERENCES user (id)<br>);</pre><p>In the review table, the author_id column references the id column in the user table. Based on this, we can move on to prepare the create.html template for the page where users write a new review:</p><pre># templates/review/create.html</pre><pre>{% extends &#39;base.html&#39; %}<br>{% block header %}<br>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h1&gt;{% block title %}Write a new review{% endblock %}&lt;/h1&gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><pre>{% block content %}<br>&lt;div class=&quot;container&quot;&gt;<br>  &lt;form method=&quot;post&quot;&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;exampleFormControlTextarea1&quot;&gt;Your review:&lt;/label&gt;<br>      &lt;textarea class=&quot;form-control&quot; rows=&quot;3&quot; name=&quot;review-text&quot;&gt;   <br>      &lt;/textarea&gt;<br>    &lt;/div&gt;<br>    &lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>  &lt;/form&gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><p>Based on the template, we can prepare a new blueprint function in review.py that processes this form:</p><pre># review.py</pre><pre>@bp.route(&#39;/create&#39;, methods=(&#39;GET&#39;, &#39;POST&#39;))<br>@login_required<br>def create():<br>  if request.method == &#39;POST&#39;:<br>    text = request.form[&#39;review-text&#39;]<br>    text = text.strip()<br>    db = get_db()<br>    error = None</pre><pre>if not text:<br>    error = &#39;You didn\&#39;t add any new reviews.&#39;<br>  if error is None:<br>    db.execute(<br>      &#39;INSERT INTO review (author_id, content) VALUES (?, ?)&#39;,   <br>      (g.user[&#39;id&#39;], text)<br>    )<br>    db.commit()<br>    return redirect(url_for(&#39;review.dashboard&#39;))</pre><pre>flash(error)</pre><pre>return render_template(&#39;review/create.html&#39;)</pre><h4>Read</h4><p>When you launch your application, log yourself in, and add a new review, it is natural to expect the newly added review to be aggregated on both the homepage and user dashboard.</p><p>To achieve this, we need to update our code for the home page template by replacing the static texts with:</p><pre># templates/review/home.html</pre><pre>...<br>{% for review in reviews %}<br>  &lt;blockquote class=&quot;blockquote&quot;&gt;<br>    &lt;p class=&quot;mb-0&quot;&gt;{{ review[&#39;content&#39;] }}&lt;/p&gt;<br>      &lt;footer class=&quot;blockquote-footer&quot;&gt;<br>        From @{{ review[&#39;username&#39;].split(&quot;@&quot;)[0] }}<br>      &lt;/footer&gt;<br>  &lt;/blockquote&gt;<br>{% endfor %}<br>...</pre><p>Additionally, we need to update the home function:</p><pre># review.py</pre><pre>@bp.route(&#39;/&#39;)<br>def home():<br>    db = get_db()<br>    reviews = db.execute(<br>        &#39;SELECT r.id, created, author_id, content, username&#39;<br>        &#39; FROM review r JOIN user u ON r.author_id = u.id&#39;<br>        &#39; ORDER BY created DESC&#39;<br>    ).fetchall()<br>    return render_template(&#39;review/home.html&#39;, reviews=reviews)</pre><p>Similarly, we need to update our code for the dashboard function. The dashboard function only selects and presents the review written by the given user.</p><pre># review.py</pre><pre>@bp.route(&#39;/dashboard&#39;)<br>@login_required<br>def dashboard():<br>  db = get_db()<br>  reviews = db.execute(<br>        &#39;SELECT r.id, created, author_id, content, username&#39;<br>        &#39; FROM review r JOIN user u ON r.author_id = u.id&#39;<br><strong>        &#39; WHERE author_id = ?&#39;</strong><br>        &#39; ORDER BY created DESC&#39;,<br><strong>        (g.user[&#39;id&#39;],)</strong><br>  ).fetchall()</pre><pre>return render_template(&#39;review/dashboard.html&#39;, reviews=reviews)</pre><p>The dashboard template uses review which is passed to the template as a hashtable, and insert the value the key id corresponds to into the links of <em>Edit</em> and <em>Delete</em>, so a user can actually edit and delete a review.</p><pre># templates/review/dashboard.html</pre><pre>&lt;p class=&quot;lead&quot;&gt;Here are your reviews:&lt;/p&gt;<br>{% for review in reviews %}<br>  &lt;blockquote class=&quot;blockquote&quot;&gt;<br>    &lt;p class=&quot;mb-0&quot;&gt;{{ review[&#39;content&#39;] }}&lt;/p&gt;<br>    &lt;footer class=&quot;blockquote-footer&quot;&gt;<br>      From @{{ review[&#39;username&#39;].split(&quot;@&quot;)[0] }}<br>      &lt;a href=&quot;<br>             <strong>{{ url_for(&#39;review.edit&#39;, id=review[&#39;id&#39;]) }}</strong>&quot;&gt;Edit&lt;/a&gt;<br>      &lt;a href=&quot;<br>         <strong>{{ url_for(&#39;review.delete&#39;, id=review[&#39;id&#39;]) }}</strong>&quot;&gt;Delete&lt;/a&gt;<br>    &lt;/footer&gt;<br>  &lt;/blockquote&gt;<br>{% endfor %}</pre><h4>Update and delete</h4><p>A user should be able to edit their given reviews on a separate page edit.html.</p><p>This page is very similar to create.html, so the code of the editing page edit.html should be almost exactly the same as create.html. However, as this is editing, the user should be able to see the original content of the review:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDMjFAnJY2kKXH_5VTzugg.png" /></figure><p>We achieve this by passing review[&#39;content&#39;] to the editing form:</p><pre># templates/review/edit.html</pre><pre>{% extends &#39;base.html&#39; %}<br>{% block header %}<br>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h1&gt;{% block title %}Update your review{% endblock %}&lt;/h1&gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><pre>{% block content %}<br>&lt;div class=&quot;container&quot;&gt;<br>  &lt;form method=&quot;post&quot;&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;exampleFormControlTextarea1&quot;&gt;<br>        Your Mean Review:<br>      &lt;/label&gt;<br>      &lt;textarea class=&quot;form-control&quot; <br>       id=&quot;exampleFormControlTextarea1&quot; rows=&quot;3&quot; name=&quot;review-text&quot;&gt;<br><strong>        {{ review[&#39;content&#39;] }}</strong><br>      &lt;/textarea&gt;<br>    &lt;/div&gt;<br>    &lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>  &lt;/form&gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><p>As for the edit and delete functions, both will need to retrieve the review. As a result, we can factor this as an independent method get_review:</p><pre># review.py</pre><pre>def get_review(id):<br>  db = get_db()<br>  review = db.execute(<br>        &#39;SELECT r.id, created, author_id, content, username&#39;<br>        &#39; FROM review r JOIN user u ON r.author_id = u.id&#39;<br>        &#39; WHERE r.id = ?&#39;,<br>        (id,)<br>  ).fetchone()</pre><pre>  if review is None:<br>    abort(404, &quot;Review id {0} doesn&#39;t exist.&quot;.format(id))</pre><pre>  if review[&#39;author_id&#39;] != g.user[&#39;id&#39;]:<br>    abort(403)</pre><pre>  return review</pre><p>Both the edit and delete functions will be able to utilize this function:</p><pre># review.py</pre><pre>@bp.route(&#39;/edit/&lt;int:id&gt;&#39;, methods=(&#39;GET&#39;, &#39;POST&#39;))<br>@login_required<br>def edit(id):<br>  review = get_review(id)</pre><pre>  if request.method == &#39;POST&#39;:<br>    text = request.form[&#39;review-text&#39;]<br>    text = text.strip()<br>        db = get_db()<br>        error = None</pre><pre>  if not text:<br>    error = &#39;You can\&#39;t update the review to nothing.&#39;<br>    if error is None:<br>    db.execute(<br>      &#39;UPDATE review SET content = ?&#39;<br>      &#39; WHERE id = ?&#39;,<br>      (text, id)<br>    )<br>    db.commit()<br>    return redirect(url_for(&#39;review.dashboard&#39;))</pre><pre>  flash(error)<br>  return render_template(&#39;review/edit.html&#39;, review=review)</pre><pre>@bp.route(&#39;/delete/&lt;int:id&gt;&#39;, methods=(&#39;GET&#39;, &#39;POST&#39;))<br>@login_required<br>def delete(id):<br>  get_review(id)<br>  db = get_db()<br>  db.execute(&#39;DELETE FROM review WHERE id = ?&#39;, (id,))<br>  db.commit()<br>  return redirect(url_for(&#39;review.dashboard&#39;))</pre><p>It is worth noting that the review ID is passed to the two functions, and their routes format the URLs as domain_name/function/review_id, like/edit/1 or /delete/2.</p><h3>Testing</h3><p>The testing of CRUD is comparatively straightforward. For instance, the test_create function will be:</p><pre>def test_create(client, auth, app):<br>  count_prior = 0<br>  count_after = 0</pre><pre>  with app.app_context():<br>    db = get_db()<br>    count_prior = db.execute(<br>        &#39;SELECT COUNT(id) FROM review&#39;).fetchone()[0]</pre><pre>  auth.login()<br>    assert client.get(&#39;/create&#39;).status_code == 200<br>    client.post(&#39;/create&#39;, <br>      data={&#39;review-text&#39;: &#39;this is a mean review&#39;})</pre><pre>  with app.app_context():<br>    db = get_db()<br>    count_after = db.execute(<br>      &#39;SELECT COUNT(id) FROM review&#39;).fetchone()[0]</pre><pre>  assert count_prior + 1 == count_after</pre><p>In addition to the testing on CRUD, we may need to test if login_required works as intended on these pages, and if only the author of a review can edit their reviews.</p><h3>Tutorial List</h3><ul><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115">Build and test a mini Flask application</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760">Build, Test, and Deploy a Flask Application: Part 1 — Templates</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc">Build, Test, and Deploy a Flask Application: Part 2 — Authentication</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21">Build, Test, and Deploy a Flask Application: Part 3 — Application Factory and Blueprints</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb">Build, Test, and Deploy a Flask Application: Part 4 — Restructuring Testing</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e">Build, Test, and Deploy a Flask Application: Part 5 — Authentication (continued)</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a">Build, Test, and Deploy a Flask Application: Part 6 — Review System</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-7-60dde9080330">Build, Test, and Deploy a Flask Application: Part 7 — Deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952a1b29a02a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a">Build, Test, and Deploy a Flask Application (Part 6)</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build, Test, and Deploy a Flask Application (Part 5)]]></title>
            <link>https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a3c0bc36b8e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Sat, 28 Dec 2019 18:47:02 GMT</pubDate>
            <atom:updated>2021-05-07T20:22:31.168Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Authentication (continued</strong>)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BXuG8KO-b0E1x6iL" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=medium&amp;utm_medium=referral">Marvin Meyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Meta Information About This Tutorial</h3><h4>Learning goals</h4><ul><li>Authentication</li></ul><p>Note: This tutorial is part of the series <a href="https://medium.com/@neohao/learn-flask-in-a-scientific-way-baf4d8055f6e"><em>Learn Flask in a scientific way</em></a><em>.</em></p><h4>Source code</h4><ul><li>The source code of this tutorial can be accessed on <a href="https://github.com/Neo-Hao/mean-review-collector">GitHub</a>.</li><li>The demo can be accessed on <a href="https://pacific-fortress-91193.herokuapp.com/">this website</a>.</li><li>The version that covers only this tutorial can be accessed <a href="https://github.com/Neo-Hao/mean-review-collector">here</a>.</li></ul><h3>Plans</h3><p>In this tutorial, we will continue our development and testing of the authentication component of our web application.</p><p>So far, we have a functioning registration page. Based on that, we will develop the login and logout functionalities, and test them thoroughly. Eventually, we want to achieve the following effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9D8ttYq4Cee8WYQUs8mJZQ.png" /><figcaption>When a user logs in, he/she will see this.</figcaption></figure><p>When the “Log Out” button is clicked, users will be directed to the home page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsz-_n6ohwYfKg8ny1z_Rw.png" /><figcaption>When a user logs out, he/she will see this.</figcaption></figure><p>Please note that the buttons (on the right side) of the navigation bar will change, depending on if users are logged in or not.</p><h3>Add Login and Logout Functionalities</h3><h4><strong>Login and logout functions</strong></h4><p>To add the login and logout functions, we need at least two more functions in auth.py: the login and the logout functions.</p><p>For the login function, when the request method is POST, two scenarios must at least be checked, including (a) when an email is never registered with the application and when (b) a username is found but the password is wrong.</p><pre># auth.py<br>@bp.route(&#39;/login&#39;, methods=(&#39;GET&#39;, &#39;POST&#39;))<br>def login():<br>    if request.method == &#39;POST&#39;:<br>        username = request.form[&#39;username&#39;]<br>        password = request.form[&#39;password&#39;]<br>        db = get_db()<br>        error = None<br>        user = db.execute(<br>            &#39;SELECT * FROM user WHERE username = ?&#39;, (username,)<br>        ).fetchone()</pre><pre>        if user is None:<br>            error = &#39;Incorrect username.&#39;<br>        elif not check_password_hash(user[&#39;password&#39;], password):<br>            error = &#39;Incorrect password.&#39;</pre><pre>        if error is None:<br>            session.clear()<br>            session[&#39;user_id&#39;] = user[&#39;id&#39;]<br>            return redirect(url_for(&#39;review.dashboard&#39;))</pre><pre>        flash(error)</pre><pre>     return render_template(&#39;auth/login.html&#39;)</pre><p>Please note that we direct users to the dashboard page when users successfully log in, but we don’t have such a page yet. We will create it soon.</p><p>The logout function is comparatively simpler:</p><pre># auth.py<br>@bp.route(&#39;/logout&#39;)<br>def logout():<br>    session.clear()<br>    return redirect(url_for(&#39;review.home&#39;))</pre><p>We simply redirect users to the home page when they log out.</p><h4>Dashboard</h4><p>The dashboard is meant for only the users who log into the service. As a result, we need to prepare a wrapper method that can be used as a decorator for other functions:</p><pre># auth.py<br>def login_required(view):<br>    @functools.wraps(view)<br>    def wrapped_view(**kwargs):<br>        if g.user is None:<br>            return redirect(url_for(&#39;auth.login&#39;))</pre><pre>        return view(**kwargs)</pre><pre>    return wrapped_view</pre><p>The view function for the dashboard page will be able to utilize this function as a login requirement decorator:</p><pre># review.py<br><a href="http://twitter.com/bp">@bp</a>.route(&#39;/dashboard&#39;)<br>@login_required<br>def dashboard():<br>    return render_template(&#39;review/dashboard.html&#39;)</pre><p>Now we can move to create the dashboard template:</p><pre># templates/review/dashboard.html<br>{% extends &#39;base.html&#39; %}</pre><pre>{% block header %}<br>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h1&gt;{% block title %}Welcome, User!{% endblock %}&lt;/h1&gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><pre>{% block content %}<br>&lt;div class=&quot;container&quot;&gt;<br>  &lt;p class=&quot;lead&quot;&gt;Want to &lt;a href=&quot;#&quot;&gt;write a mean review&lt;/a&gt;?&lt;/p&gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><p>The dashboard template extends the base template, and doesn’t contain much information at this point.</p><h4>Adaptive navigation bar</h4><p>We intend for the navigation bar to have different buttons, depending on if users have logged in or not. To achieve this, we rely on the session that is initiated when a user logs in:</p><pre># templates/base.html<br>{% if session.get(&#39;user_id&#39;) is none %}<br>  &lt;li class=&quot;nav-item&quot;&gt;<br>    &lt;a class=&quot;nav-link&quot; <br>       href=&quot;{{url_for(&#39;auth.register&#39;)}}&quot;&gt;Register&lt;/a&gt;<br>  &lt;/li&gt;<br>  &lt;li class=&quot;nav-item&quot;&gt;<br>    &lt;a class=&quot;nav-link&quot; <br>       href=&quot;{{ url_for(&#39;auth.login&#39;) }}&quot;&gt;Login&lt;/a&gt;<br>  &lt;/li&gt;<br>{% else %}<br>  &lt;li class=&quot;nav-item&quot;&gt;<br>    &lt;a class=&quot;nav-link&quot; <br>       href=&quot;{{ url_for(&#39;review.dashboard&#39;) }}&quot;&gt;My Account&lt;/a&gt;<br>  &lt;/li&gt;<br>  &lt;li class=&quot;nav-item&quot;&gt;<br>    &lt;a class=&quot;nav-link&quot; <br>       href=&quot;{{ url_for(&#39;auth.logout&#39;) }}&quot;&gt;Log Out&lt;/a&gt;<br>  &lt;/li&gt;<br>{% endif %}</pre><p>When the session with the specified user ID is none, it means that there are no logged-in users, so we present “Registration” and “Login” buttons. Otherwise, we present “My Account” and “Log Out” buttons.</p><h3>Test Login and Logout Functions</h3><p>To test a successful login, we need to have user info (i.e. email address and password) stored in our database. To achieve this, we can update our code to insert a testing user into our database before the execution of all test cases:</p><pre># conftest.py<br>import ...</pre><pre>with open(os.path.join(os.path.dirname(__file__), &#39;data.sql&#39;), &#39;rb&#39;) as f:<br>    _data_sql = f.read().decode(&#39;utf8&#39;)</pre><pre>...</pre><pre>with app.app_context():<br>        init_db()<br>        get_db().executescript(_data_sql)</pre><pre>yield app</pre><p>In data.sql, we only insert one entry:</p><pre># data.sql<br>INSERT INTO user (username, password)<br>VALUES<br>  (&#39;cat@cat.com&#39;, &#39;pbkdf2:sh...&#39;);</pre><p>Based on this, we can move on to add a few more testing functions that test login and logout.</p><p>If we have multiple different scenarios, we may end up with a lot of redundant login code. To reduce redundancy, we can factor the login and logout code to a class that resides in conftest.py.</p><pre># conftest.py</pre><pre>@pytest.fixture<br>def client(app):<br>  return app.test_client()</pre><pre>class AuthActions(object):<br>  def __init__(self, client):<br>    self._client = client</pre><pre>  def login(self, username=&#39;cat@cat.com&#39;, password=&#39;test&#39;):<br>    return self._client.post(<br>      &#39;/login&#39;,<br>      data={&#39;username&#39;: username, &#39;password&#39;: password}<br>    )</pre><pre>  def logout(self):<br>    return self._client.get(&#39;/logout&#39;)</pre><pre>@pytest.fixture<br>def auth(client):<br>  return AuthActions(client)</pre><p>In the above code, we are essentially taking advantage of pytest fixture objects again. The function auth will always return an auth object; an auth object is an AuthActions object and it takes a client object as the only parameter and operates on it.</p><p>This leads to that you can use two simple functions to achieve login and logout whenever you want:</p><ul><li>auth.login(): This will log you into the web application.</li><li>auth.logout(): This will log you out.</li></ul><p>With these two functions at hand, we can move on to test login and logout functionalities:</p><pre>def test_login(client, auth):<br>  assert client.get(&#39;/login&#39;).status_code == 200<br>  response = auth.login()<br>  assert response.headers[&#39;Location&#39;] == <br>                               &#39;http://localhost/dashboard&#39;  <br>  with client:<br>    client.get(&#39;/&#39;)<br>    assert session[&#39;user_id&#39;] == 1<br>    assert g.user[&#39;username&#39;] == &#39;cat@cat.com&#39;</pre><pre>def test_logout(client, auth):<br>  auth.login()<br>  with client:<br>    auth.logout()<br>    assert &#39;user_id&#39; not in session</pre><h3>Tutorial List</h3><ul><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115">Build and test a mini Flask application</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760">Build, Test, and Deploy a Flask Application: Part 1 — Templates</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc">Build, Test, and Deploy a Flask Application: Part 2 — Authentication</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21">Build, Test, and Deploy a Flask Application: Part 3 — Application Factory and Blueprints</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb">Build, Test, and Deploy a Flask Application: Part 4 — Restructuring Testing</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e">Build, Test, and Deploy a Flask Application: Part 5 — Authentication (continued)</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a">Build, Test, and Deploy a Flask Application: Part 6 — Review System</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-7-60dde9080330">Build, Test, and Deploy a Flask Application: Part 7 — Deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a3c0bc36b8e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e">Build, Test, and Deploy a Flask Application (Part 5)</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build, Test, and Deploy a Flask Application: Part 4]]></title>
            <link>https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aa4f079fadb</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Sun, 15 Dec 2019 06:12:25 GMT</pubDate>
            <atom:updated>2019-12-28T18:50:58.313Z</atom:updated>
            <content:encoded><![CDATA[<h4>Restructuring testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5XKehWiJPCtTNnkS" /><figcaption>Photo by <a href="https://unsplash.com/@yomex4life?utm_source=medium&amp;utm_medium=referral">Yomex Owo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Meta Information About This Tutorial</h3><h4>Learning goals</h4><ul><li>Unit testing</li></ul><p>Note: This tutorial is part of the series <a href="https://medium.com/@neohao/learn-flask-in-a-scientific-way-baf4d8055f6e"><em>Learn Flask in a scientific way</em></a><em>.</em></p><h4>Source code</h4><ul><li>The source code of this tutorial can be accessed on <a href="https://github.com/Neo-Hao/mean-review-collector">GitHub</a>.</li><li>The demo can be accessed at <a href="https://pacific-fortress-91193.herokuapp.com/">https://pacific-fortress-91193.herokuapp.com/</a>.</li><li>The version that covers only this tutorial can be accessed <a href="https://github.com/Neo-Hao/mean-review-collector/tree/249a754ec97fcbb984d529aa834058b0ce0b250f">here</a>.</li></ul><h3>Install Your Application as a Package</h3><p>As we move to use Application Factory and Blueprints, our testing code also needs some upgrade. To make our application that adopts Application Factory and Blueprints visible to testing code underneath a different folder, we need to install our application as a package first. There are three steps to achieve this.</p><p>First, we need to record all the package dependencies. This is important, especially when you need to replicate what you have in a different machine/virtual environment (e.g., deployment). To do so, navigate to the root of the directory (mean-review-collector) through your terminal and type:</p><pre>(env) $ pip freeze &gt;requirements.txt</pre><p>You will see a file requirements.txt generated at the root directory that contains both package names and their exact version numbers.</p><pre>Flask==1.1.1<br>Jinja2==2.10.3<br>...<br>wcwidth==0.1.7<br>Werkzeug==0.16.0<br>zipp==0.6.0</pre><p>When you want to build a replica in a different virtual environment, you can just type:</p><pre>(env) $ pip install -r requirements.txt MANIFEST.in</pre><p>Second, we need to describe our project. The description relies on two files: setup.py and MANIFEST.IN. These two files are needed to make our app installable. setup.py contains the basic information about our application:</p><pre>from setuptools import find_packages, setup</pre><pre>setup(<br>    name=&#39;app&#39;,<br>    version=&#39;0.1&#39;,<br>    packages=find_packages(),<br>    include_package_data=True,<br>    zip_safe=False,<br>    install_requires=[<br>        &#39;flask&#39;,<br>    ],<br>)</pre><p>include_package_data=True indicates that we want to include extra data for this project. MANIFEST.IN includes basic information about the data of this project, such as templates and sql file:</p><pre>include app/schema.sql<br>graft app/static<br>graft app/templates<br>global-exclude *.pyc</pre><p>Third, we need to install our own code in app as a package. Using pip install, the installation is only one line:</p><pre>(env)$ pip install -e .</pre><p>However, install deserves some detailed explanation. Normally, when you install Python packages through pip nstall, pip looks for the target package in the Python Package Index. However, pip can also look for packages which are in other places (e.g., code in your local machine).</p><p>The above one-line code essentially copies your code over to the env folder and treats it like any other package you&#39;ve installed in this virtual environment. The dot refers to your current directory. The flag -e makes it an editable install — if you make further changes to the files inside the project folder, those will be automatically reflected in the env folder as well.</p><p>Now you can check all the installed packages in this virtual environment:</p><pre>(env)$ pip list</pre><p>You will see something like:</p><pre>Package            Version Location                               <br>------------------ ------- ---------------------------------------<br>app                0.1     /home/qiang/repos/mean-review-collector<br>attrs              19.3.0  <br>Click              7.0     <br>Flask              1.1.1   <br>...</pre><h3>Unit Testing</h3><p>The next thing we do is to rewrite our unit testing cases. We used unittest simply for convenience. From now on, we will switch from unittest to pytest. Although pytest is not in the standard library of Python, it is better than unittestin many ways. To install pytest and another tool coverage (that measures code coverage of your testing), we just need to type through your terminal:</p><pre>(env)$ pip install pytest coverage</pre><p>By default, pytest only identifies the test files or methods whose names start with test_ or end with _test. We have at least three areas to test, including the factory, the database, and the authentication, so we need three files underneath tests directory:</p><pre>mean-review-collector<br> - env<br> - app<br> - instance<br> - tests   <br>   - test_auth.py<br>   - test_db.py<br>   - test_factory.py</pre><p>When all the test code is ready, you can run all of them by simply typing pytest to your terminal, and you may see something similar to:</p><pre>(env)$ pytest<br>=============== test session starts ===========================<br>platform linux -- Python 3.7.4, pytest-5.3.1, py-1.8.0, pluggy-0.13.1<br>rootdir: /home/qiang/repos/mean-review-collector<br>collected 7 items</pre><pre>tests/test_auth.py .. [ 42%]<br>tests/test_db.py .. [ 71%]<br>tests/test_factory.py .. [100%]</pre><p>Before we rush to write the testing code in each file, we should recognize that certain code always needs to be executed first before any unit testing, such as connecting to the database and initiating an application object. pytest uses fixture to take care of such code. The purpose of fixtures is to provide a fixed baseline upon which tests can reliably and repeatedly execute. To achieve this, we would put such code in a different file named conftest.py. For instance, we certainly need some code to help us initiate an application object:</p><pre>#conftest.py</pre><pre>@pytest.fixture<br>def app():<br>  db_fd, db_path = tempfile.mkstemp()</pre><pre>  app = create_app({<br>        &#39;TESTING&#39;: True,<br>        &#39;DATABASE&#39;: db_path,<br>  })</pre><pre>  with app.app_context():<br>        init_db()</pre><pre>  yield app</pre><pre>  os.close(db_fd)<br>  os.unlink(db_path)</pre><p>pytest uses the decorator to identify a function as a fixture — a function that should be executed first before each testing.</p><p>Although the testing on database and authentication was rather similar to our old testing code that used unittest, there are still two differences that we want to highlight.</p><p>First, parametrize can be used to test various inputs against a function:</p><pre># test_auth.py</pre><pre>@pytest.mark.parametrize((&#39;username&#39;, &#39;password&#39;, &#39;message&#39;), (<br>  (&#39;&#39;, &#39;&#39;, b&#39;Username is required.&#39;),<br>  (&#39;<a href="/service/mailto:a@c.com">a@c.com</a>&#39;, &#39;&#39;, b&#39;Password is required.&#39;),<br>  (&#39;<a href="/service/mailto:a@b.com">a@b.com</a>&#39;, &#39;test&#39;, b&#39;already registered&#39;),<br>))<br>def test_register_validate_input(client, username, password, message):<br>  response = client.post(<br>    &#39;/register&#39;,<br>    data={&#39;username&#39;: username, &#39;password&#39;: password}<br>  )<br>  assert message in response.data</pre><p>This is achieved using pytest.mark decorators for testing functions.</p><p>Second, monkeypatch can be a useful tool for testing. The following code essentially follows the guidance of <a href="https://flask.palletsprojects.com/en/1.1.x/tutorial/tests/">Flask’s official tutorial</a>:</p><pre>def test_init_db_command(runner, monkeypatch):<br>  class Recorder(object):<br>    called = False</pre><pre>  def fake_init_db():<br>    Recorder.called = True</pre><pre>  monkeypatch.setattr(&#39;app.db.init_db&#39;, fake_init_db)<br>  result = runner.invoke(args=[&#39;init-db&#39;])<br>  assert &#39;Initialized&#39; in result.output<br>  assert Recorder.called</pre><p>However, the official tutorial doesn’t really explain monkeypatch. monkeypatch dynamically changes a piece of software (e.g., a module, object, method, or function) at runtime. Pytest uses this feature to allow the testing of functions or methods that you don’t want to actually execute.</p><p>For instance, we have a function named get_info as the following:</p><pre>def get_info():<br>  <em>&quot;&quot;&quot;<br>  call GET for http://XXX/get<br>  returns status code and url in HTTP response<br>  &quot;&quot;&quot;<br>  </em>r = requests.get(base_url + &#39;get&#39;)<br><br>  if r.status_code != 200:<br>    return r.status_code, &#39;&#39;<br>  else:<br>    response_data = r.json()<br>    return r.status_code, response_data[&quot;url&quot;]</pre><p>We can test this function out without making it actually send an HTTP request by using monkeypatch:</p><pre>def test_get_info(monkeypatch):<em><br>  </em>class ResponseMock(object):<br>    def __init__(self):<br>      self.status_code = 200<br>      self.url = &#39;&#39;<br>      self.headers = {}<br><br>    def json(self):<br>      return {&#39;account&#39;: &#39;123&#39;,&#39;url&#39;: &#39;http://test.com&#39;}<br><br>    def get_patched(url):<br>        return ResponseMock()<br><br>    monkeypatch.setattr(requests, &#39;get&#39;, get_patched)<br>    assert get_info() == (200, &#39;http://test.com&#39;)</pre><p>What monkeypatch realizes here is essentially to replace the behavior of requests.get() with what you have defined under get_patched. Similarly, in our test_init_db_command method:</p><pre>monkeypatch.setattr(&#39;app.db.init_db&#39;, fake_init_db)</pre><p>We essentially attached some new behavior to app.db.init_db. The new behavior is being defined under fake_init_db. The only thing this method actually achieves is adding a new field Recorder.called for app.db.init_db to keep track of whether it gets executed or not.</p><p>Please check out the final code of our restructured unit testing <a href="https://github.com/Neo-Hao/mean-review-collector/tree/249a754ec97fcbb984d529aa834058b0ce0b250f">here</a>.</p><h3>Tutorial List</h3><ul><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115">Build and test a mini Flask application</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760">Build, Test, and Deploy a Flask Application: Part 1 — Templates</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc">Build, Test, and Deploy a Flask Application: Part 2 — Authentication</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21">Build, Test, and Deploy a Flask Application: Part 3 — Application Factory and Blueprints</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb">Build, Test, and Deploy a Flask Application: Part 4 — Restructuring Testing</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e">Build, Test, and Deploy a Flask Application: Part 5 — Authentication (continued)</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a">Build, Test, and Deploy a Flask Application: Part 6 — Review System</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-7-60dde9080330">Build, Test, and Deploy a Flask Application: Part 7 — Deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aa4f079fadb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb">Build, Test, and Deploy a Flask Application: Part 4</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build, Test, and Deploy a Flask Application (Part 3)]]></title>
            <link>https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a2abfe4be21</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Sat, 07 Dec 2019 19:58:40 GMT</pubDate>
            <atom:updated>2021-05-07T17:17:17.956Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build, Test, and Deploy a Flask Application: Part 3</h3><h4>Use Application Factory and Blueprints</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DEMTs5jTm1Z0q2X6" /><figcaption>Photo by <a href="https://unsplash.com/@szolkin?utm_source=medium&amp;utm_medium=referral">Sergey Zolkin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Meta Information About This Tutorial</h3><h4>Learning goals</h4><ul><li>Restructure a <a href="https://www.palletsprojects.com/p/flask/">Flask</a> project from a single script application to using an Application Factory and blueprints.</li></ul><p>Note: This tutorial is part of the series <a href="https://medium.com/@neohao/learn-flask-in-a-scientific-way-baf4d8055f6e"><em>Learn Flask in a scientific way</em></a><em>.</em></p><h4>Source code</h4><ul><li>The source code of this tutorial can be accessed on <a href="https://github.com/Neo-Hao/mean-review-collector">GitHub</a>.</li><li>The demo can be accessed at <a href="https://pacific-fortress-91193.herokuapp.com/">https://pacific-fortress-91193.herokuapp.com/</a>.</li><li>The version of the single script application can be accessed <a href="https://github.com/Neo-Hao/mean-review-collector/tree/ecd52a0af58ab1b1165491d50afdd355dfb9988f">on GitHub</a>.</li></ul><h3>Application Factory and Blueprints — What Are They and Why Do We Need Them?</h3><p>Continuing from the last tutorial, we already have an application with tested registration functionality.</p><p>However, everything was coded in a single file, app.py. This approach is convenient but doesn’t scale well. When the complexity increases, a single file application can be very problematic.</p><p>Although Flask doesn’t impose a strict organization for application projects, there are several recommended approaches. Nearly all of them involve the usage of Application Factory and blueprints.</p><p>Application Factory is simply a function that is responsible for creating the application object and its configuration. It can also create multiple application objects if needed.</p><p>When everything resides in a single app.py file, the application object will be created once the script is executed. By then, it is impossible to apply further configuration changes.</p><p>In contrast, an Application Factory delays the creation of the application object — there are no application instances initialized. Therefore, it is possible to apply configuration changes dynamically and even create multiple application objects.</p><p>A typical Application Factory looks like this:</p><pre>#__init__.py</pre><pre>from flask import Flask<br># import more</pre><pre>def create_app(config_file=None):<br>    # create and configure the app<br>    app = Flask(__name__)</pre><pre>    # configuration<br>    if (config_name is not None):<br>       app.config.from_pyfile(config_file, silent=True)<br>    else:<br>       app.config.from_mapping(<br>         SECRET_KEY=&#39;sdfigtertairasgkd8dty60546j4563l43563&#39;,<br>         DATABASE=os.path.join(app.instance_path, &#39;app.sqlite&#39;),<br>    )</pre><pre>    # attach routes/views and database functions</pre><pre>    return app</pre><p>The create_app() function is the Application Factory, which takes the configuration file as the parameter. The configuration file defaults to None. When no configuration name is specified, a simple configuration will be set up underneath the else branch.</p><p>Once the application object is created, it can be further configured and other functions (e.g., database, views) can be initialized. In the end, the factory function will create and return an application instance.</p><p>Blueprints are a set of .py files that organize groups of related routes and views functions. It is natural that functions that deal with authentication should be organized in a file separate from functions that deal with errors.</p><p>In addition to this, blueprints also address a complication introduced by using the Application Factory. In a single script application, the application object is created first to allow the app.route decorator to work.</p><p>When using an Application Factory, the application object is created at runtime, which makes it too late for routes and review functions to work in the same way.</p><p>To resolve this complication, a blueprint associates routes functions with itself in a dormant state until the blueprint registers with the application.</p><p>A typical blueprint looks like this:</p><pre>#auth.py<br>from flask import Blueprint</pre><pre>bp = Blueprint(&#39;auth&#39;, __name__)</pre><pre><a href="http://twitter.com/bp">@bp</a>.route(&#39;/register&#39;, methods=(&#39;GET&#39;, &#39;POST&#39;))<br>def register():</pre><pre>   # register stuff</pre><pre>   return render_template(&#39;auth/register.html&#39;)</pre><p>The registration of a blueprint looks like this:</p><pre>#__init__.py</pre><pre>from flask import Flask<br># import more</pre><pre>def create_app(config_file=None):<br>    # create and configure the app<br>    app = Flask(__name__)</pre><pre>    # configuration stuff</pre><pre>    # attach routes/views and database functions<br><strong>    from . import auth<br>    app.register_blueprint(auth.bp)</strong></pre><pre>    return app</pre><h3>Overall Restructuring</h3><p>To utilize Application Factory and blueprints, we need to restructure our application to:</p><pre>mean-review-collector<br>---app<br>  ---templates<br>    ---base.html<br>    ---etc.<br>  ---__init__.py<br>  ---errors.py<br>  ---auth.py<br>  ---review.py<br>  ---db.py<br>  ---schema.sql<br>---tests<br>---instance<br>  ---app.sqlite<br>---env</pre><p>The application package will live inside the app folder. Test cases will live inside the test folder. The database will live inside the instance folder.</p><p>Same as before, the env folder still holds the virtual environment configuration. This structure will come handy when we need to make the app application installable later.</p><h3>Application Factory</h3><p>The Application Factory lives inside __init__.py, underneath the app folder:</p><pre>#__init__.py</pre><pre>import os<br>from flask import Flask</pre><pre>def create_app(config_file=None):<br>    # create and configure the app<br>    app = Flask(__name__)</pre><pre>    # configuration<br>    if (config_name is not None):<br>       app.config.from_pyfile(config_file, silent=True)<br>    else:<br>       app.config.from_mapping(<br>         SECRET_KEY=&#39;sdfigtertairasgkd8dty60546j4563l43563&#39;,<br>         DATABASE=os.path.join(app.instance_path, &#39;app.sqlite&#39;),<br>    )</pre><pre>    # attach routes/views and database functions</pre><pre>    return app</pre><p>It is worth noting that our Application Factory is incomplete in the current state.</p><p>When we finish the functions relevant to the database and blueprints, we will register those to the Application Factory, and update the create_app() function.</p><h3>Database</h3><p>We will factor all functions related to the database to a single script, db.py. While most functions will stay the same, some differences are still notable:</p><pre>#db.py</pre><pre>import sqlite3<br>import click<br>from flask import current_app, g</pre><pre># more functions</pre><pre># create the database<br>def init_db():<br>    db = get_db()<br>    with current_app.open_resource(&#39;schema.sql&#39;) as f:<br>        db.executescript(f.read().decode(&#39;utf8&#39;))</pre><pre>@click.command(&#39;init-db&#39;)<br>@with_appcontext<br>def init_db_command():<br>    &quot;&quot;&quot;Clear the existing data and create new tables.&quot;&quot;&quot;<br>    init_db()<br>    click.echo(&#39;Initialized the database.&#39;)</pre><pre># more functions</pre><p>First, all the functions in db.py are created when there is no application object being created. As a result, we don’t have access to the object app that we created before.</p><p>However, sometimes, we do need to refer to the object. A workaround is to use current_app. current_app is typically used as a proxy to the application so you can handle all the requests when you adopt the pattern of Application Factory and blueprints.</p><p>A close comparison of the init_db method can demonstrate this point more clearly:</p><pre># app.py<br># create the database -- when you have access to app object<br>def init_db():    <br>  with app.app_context():        <br>    db = get_db()        <br>    with app.open_resource(&#39;schema.sql&#39;, mode=&#39;r&#39;) as f:<br>      db.cursor().executescript(f.read())        <br>      db.commit()</pre><pre># db.py<br># create the database -- when you adopt application factory<br>def init_db():<br>  db = get_db()<br>  with <strong>current_app</strong>.open_resource(&#39;schema.sql&#39;, mode=&#39;r&#39;) as f:<br>    db.cursor().executescript(f.read())        <br>    db.commit()</pre><p>Second, we need to create a function, init_db_command, as a command that we can run through the terminal. We will no longer have access to the created app object.</p><p>As a result, we can no longer initiate the database in the same way as we did in part 2. We need to associate all the database functions to our Application Factory:</p><pre>#__init__.py</pre><pre>import os<br>from flask import Flask</pre><pre>def create_app(config_file=None):<br>    # create and configure the app<br>    app = Flask(__name__)</pre><pre>    # configuration</pre><pre>    # attach routes/views and database functions<br><strong>    from . import db<br>    db.init_app(app)</strong></pre><pre>    return app</pre><p>After that, we will be able to initialize the database by typing the following in the terminal:</p><pre>flask init-db</pre><h3>Blueprints and Templates</h3><p>To make our templates more organized, we will restructure our template folder to:</p><pre>templates<br>  --base.html<br>  auth<br>    --login.html<br>    --register.html<br>  review<br>    --home.html<br>    --about.html<br>    --error.html</pre><p>We will factor all functions related to the routes and views to two different blueprint files:</p><ul><li>auth.py: Functions related to authentication.</li><li>review.py: Functions related to non-authentication pages (e.g., view mean reviews, add a mean review, update an existing review).</li></ul><p>For instance, auth.py will contain:</p><pre>#auth.py</pre><pre>from flask import Blueprint<br># import more</pre><pre>bp = Blueprint(&#39;auth&#39;, __name__)</pre><pre>@<strong>bp</strong>.route(&#39;/login&#39;)<br>def login():<br>    return render_template(&#39;auth/login.html&#39;)</pre><pre>@<strong>bp</strong>.route(&#39;/register&#39;, methods=(&#39;GET&#39;, &#39;POST&#39;))<br>def register():<br>  # many cases</pre><pre>  if error is None:<br>    db.execute(<br>      &#39;INSERT INTO user (username, password) VALUES (?, ?)&#39;,<br>      (username, generate_password_hash(password))<br>    )<br>    db.commit()<br>    return redirect(url_for(&#39;<strong>auth.login</strong>&#39;))</pre><pre>  flash(error)</pre><pre>  return render_template(&#39;<strong>auth/register.html</strong>&#39;)</pre><p>There are two things that are worth our attention.</p><p>First, all routes are associated with the blueprints, which stays in a dormant state until they are registered with the application. The registration works like this:</p><pre>#__init__.py</pre><pre>import os<br>from flask import Flask</pre><pre>def create_app(config_file=None):<br>    # create and configure the app<br>    app = Flask(__name__)</pre><pre>    # configuration</pre><pre>    # attach routes/views and database functions<br>    from . import db<br>    db.init_app(app)</pre><pre><strong>    from . import auth<br>    app.register_blueprint(auth.bp)</strong></pre><pre>    return app</pre><p>Second, the endpoint of view functions always has blueprint names prepended to it.</p><p>For instance, the endpoint for the above login function is auth.login because the login function is added to the auth blueprint. As a result, you also need to update all the endpoints in base.html to reflect this (the base template contains the navigation bar):</p><pre>&lt;li class=&quot;nav-item&quot;&gt;<br> &lt;a class=&quot;nav-link&quot; href=&quot;{{ url_for(&#39;<strong>auth.register</strong>&#39;) }}&quot;&gt;Register&lt;/a&gt;<br>&lt;/li&gt;<br>&lt;li class=&quot;nav-item&quot;&gt;<br> &lt;a class=&quot;nav-link&quot; href=&quot;{{ url_for(&#39;<strong>auth.login</strong>&#39;) }}&quot;&gt;Login&lt;/a&gt;<br>&lt;/li&gt;</pre><h3>Run the Restructured Application</h3><p>We will be ready to run the script after all the changes. If you are using Linux or Mac, run the following three lines through the terminal:</p><pre>export FLASK_APP=app<br>export FLASK_ENV=development<br>flask run</pre><p>If you are using Windows, run the following three lines through CMD:</p><pre>set FLASK_APP=app<br>set FLASK_ENV=development<br>flask run</pre><p>You will be able to see exactly the same effect as in the single script application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*O3aLU7WySFdLLUJ_WGJbBQ.png" /></figure><p>So far, we’ve covered restructuring a Flask project from a single script application to using an Application Factory and blueprints.</p><p>However, our restructuring also breaks our testing. We will leave restructuring our testing for the next tutorial.</p><p>It takes a week longer than expected to finish this piece, my school is on a quarter-based system. As the end of a quarter approaches, many things popped up to stop me from writing.</p><p>If you are still at school, this is likely to be your last or second last week, and I hope you to have a wonderful winter break. If you are working, I hope you have a great holiday soon.</p><h3>Tutorial List</h3><ul><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115">Build and test a mini Flask application</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760">Build, Test, and Deploy a Flask Application: Part 1 — Templates</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc">Build, Test, and Deploy a Flask Application: Part 2 — Authentication</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21">Build, Test, and Deploy a Flask Application: Part 3 — Application Factory and Blueprints</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb">Build, Test, and Deploy a Flask Application: Part 4 — Restructuring Testing</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e">Build, Test, and Deploy a Flask Application: Part 5 — Authentication (continued)</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a">Build, Test, and Deploy a Flask Application: Part 6 — Review System</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-7-60dde9080330">Build, Test, and Deploy a Flask Application: Part 7 — Deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a2abfe4be21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21">Build, Test, and Deploy a Flask Application (Part 3)</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build, Test, and Deploy a Flask Application — Part 2]]></title>
            <link>https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/53f2c8df3ebc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Sat, 23 Nov 2019 08:00:25 GMT</pubDate>
            <atom:updated>2019-12-28T18:50:15.155Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build, Test, and Deploy a Flask Application: Part 2</h3><h4>User authentication - registration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nz8xTggl2AtQB3xl" /><figcaption>Photo by <a href="https://unsplash.com/@bernardhermant?utm_source=medium&amp;utm_medium=referral">Bernard Hermant</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Meta Information About This Tutorial</h3><h4>Learning goals</h4><ul><li>User authentication — Registration</li></ul><p>Note: This tutorial is part of the series <a href="https://medium.com/@neohao/learn-flask-in-a-scientific-way-baf4d8055f6e"><em>Learn Flask in a scientific way</em></a><em>.</em></p><h4>Source code</h4><ul><li>The source code of this tutorial can be accessed on <a href="https://github.com/Neo-Hao/mean-review-collector">GitHub</a>.</li><li>The demo can be accessed at <a href="https://pacific-fortress-91193.herokuapp.com/">https://pacific-fortress-91193.herokuapp.com/</a>.</li><li>The version that covers only this tutorial can be accessed <a href="https://github.com/Neo-Hao/mean-review-collector/tree/ecd52a0af58ab1b1165491d50afdd355dfb9988f">here</a>.</li></ul><h3>Planning and Design</h3><p>Our goal is to set up user registration in our application. To achieve this, we need a database table that stores user information. The table contains at least three columns:</p><ol><li>ID</li><li>Username</li><li>Password</li></ol><p>Username has to be unique for each user. The route/view functions have to take this into consideration. Templates for both registration and login need to be updated to send data to the database.</p><p>In addition, the template page for when users log in needs to extend the base template we prepared in the last tutorial.</p><h3>Database Setup</h3><p>We will use an <a href="https://www.sqlite.org/">SQLite</a> database to store user information. Python comes with built-in support for SQLite in the <a href="https://docs.python.org/3.4/library/sqlite3.html">sqlite3</a> module.</p><p>To set up the database, we need to prepare an SQL file in the root level of our application, so our application structure will look like:</p><pre>--- app.py<br>--- app.test.py<br>--- templates<br>       --- html files<br><strong>--- schema.sql</strong></pre><p>This SQL file (schema.sql) contains SQL commands that create an empty table with three fields as we planned:</p><pre>DROP TABLE IF EXISTS user;</pre><pre>CREATE TABLE user (<br>  id INTEGER PRIMARY KEY AUTOINCREMENT,<br>  username TEXT UNIQUE NOT NULL,<br>  password TEXT NOT NULL<br>);</pre><p>ID is the primary key in this table, and is set to auto-increment. A primary key uniquely identifies each record in a table, and can also serve as the instrument to establish a relationship between tables.</p><p>Additionally, we are explicit that it has to be UNIQUE for username.</p><p>While the SQL command in schema is set up already, we still need Python code to execute it. Update your app.py to include more configurations and four more database functions:</p><pre># imports<br>from flask import Flask, request, g, redirect, url_for, \<br>                  render_template, flash, make_response<br>from werkzeug.security import check_password_hash, generate_password_hash<br>import sqlite3</pre><pre># configuration<br>app = Flask(__name__)<br>app.config[&quot;SECRET_KEY&quot;] = &quot;rajsiosorqwnejrq39834tergm4&quot;<br>app.config[&#39;DATABASE&#39;] = &#39;flaskr.db&#39;<br>app.config[&#39;DEBUG&#39;] = True</pre><pre># connect to database<br>def connect_db():<br>    rv = sqlite3.connect(app.config[&#39;DATABASE&#39;])<br>    rv.row_factory = sqlite3.Row<br>    return rv</pre><pre># create the database<br>def init_db():<br>    with app.app_context():<br>        db = get_db()<br>        with app.open_resource(&#39;schema.sql&#39;, mode=&#39;r&#39;) as f:<br>            db.cursor().executescript(f.read())<br>        db.commit()</pre><pre># open database connection<br>def get_db():<br>    if not hasattr(g, &#39;sqlite_db&#39;):<br>        g.sqlite_db = connect_db()<br>    return g.sqlite_db</pre><pre># close database connection<br>@app.teardown_appcontext<br>def close_db(error):<br>    if hasattr(g, &#39;sqlite_db&#39;):<br>        g.sqlite_db.close()</pre><pre>// ...</pre><p>There are two things that need explanation:</p><h4><strong>app.config</strong></h4><p>Every Flask application has a global config object named app.config. This config object can be treated just like a Python dictionary, through which you can access, assign, and modify values of configuration variables.</p><p>It is worth noting that we directly update these variables through app.config. This method only works well for small applications like ours.</p><h4><strong>g</strong></h4><p>The g object makes things global.</p><p>A Flask application typically runs on a few .py files. The g object allows you to make things global across your files in your application.</p><p>So far, we didn’t take advantage of either factories or blueprints, and are still only using one .py file, so we don’t really get a chance to taste how this is used yet. However, it is still worth knowing what the g object does.</p><p>Now, let’s initialize a database through Python shell:</p><pre>python3<br>&gt;&gt;&gt; from app import init_db<br>&gt;&gt;&gt; init_db()</pre><p>If running without errors, you will see that the database file will appear in the same directory:</p><pre>--- app.py<br>--- app.test.py<br>--- templates<br>       --- html files<br>--- schema.sql<br><strong>--- flaskr.db</strong></pre><h4><strong>Database testing</strong></h4><p>To test if the database is successfully created, we can further expand our app.test.py with another unit testing method underneath the BasicTestCase class:</p><pre>def test_database(self):<br>    tester = os.path.exists(&quot;flaskr.db&quot;)<br>    self.assertTrue(tester)</pre><h3>Registration</h3><p>With the database set up, we can move to update the registration component of our application.</p><p>Before we start, we need to make sure that you understand the difference between POST and GET requests.</p><p>If this is the first time you’ve heard of such terms, please refer to <a href="https://www.diffen.com/difference/GET-vs-POST-HTTP-Requests">this tutorial</a> to gain a conceptual understanding of POST and GET requests first.</p><p>There are three parts of the registration component that need to be updated:</p><ol><li>Route function</li><li>View function</li><li>Template</li></ol><p>We will follow this order to update them all: register.html (template) -&gt; route and view functions -&gt; base.html (template).</p><h4><strong>Template (register.html)</strong></h4><p>If you recall what we did in the last tutorial, we successfully styled the registration template, yet the registration form was not functioning, because our form doesn’t have a method attribute, and input fields don’t have name attributes:</p><pre>&lt;form&gt;<br> ...      <br>&lt;input type=&quot;email&quot; class=&quot;form-control&quot; id=&quot;email&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter email&quot;&gt;<br>...<br>&lt;input type=&quot;password&quot; class=&quot;form-control&quot; id=&quot;user-password&quot; placeholder=&quot;Password&quot;&gt;<br>...<br>&lt;/form&gt;</pre><p>For the post request to be sent and processed successfully, we will update the template by adding such attributes:</p><pre>&lt;form <strong>method=&quot;post&quot;</strong>&gt;<br> ...      <br>&lt;input type=&quot;email&quot; class=&quot;form-control&quot; id=&quot;email&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter email&quot; <strong>name=&quot;username&quot;</strong>&gt;<br>...<br>&lt;input type=&quot;password&quot; class=&quot;form-control&quot; id=&quot;user-password&quot; placeholder=&quot;Password&quot; <strong>name=&quot;password&quot;</strong>&gt;<br>...<br>&lt;/form&gt;</pre><p>It is worth noting that the ID of a form input element has nothing to do with the data contained within the element.</p><p>However, the name attribute is used in the HTTP request sent by a browser to the server as a variable name (associated with the data contained in the value attribute).</p><h4><strong>Route and view functions</strong></h4><p>The route needs to be updated to account for different types of HTTP requests, including GET and POST. The updated route should look like:</p><pre>@app.route(&#39;/register&#39;, methods=(&#39;GET&#39;, &#39;POST&#39;))</pre><p>The view function needs to account for different types of HTTP requests, deal with different scenarios of user interactions, and render possibly different views for those scenarios.</p><p>Such scenarios include:</p><ul><li>Successful registration -&gt; redirect users to log-in page.</li><li>No username (when users still click submit button).</li><li>No password (when users still click submit button).</li><li>The same username is already registered.</li></ul><p>For the first scenario, we need to commit the registration information to our database and redirect users to a different page (e.g., log-in page).</p><p>For the last three scenarios, we need to inform users of such errors and make them stay on the same page.</p><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/register&#39;, methods=(&#39;GET&#39;, &#39;POST&#39;))<br>def register():<br>    if request.method == &#39;POST&#39;:<br>        username = request.form[&#39;username&#39;]<br>        password = request.form[&#39;password&#39;]<br>        db = get_db()<br>        error = None</pre><pre>        if not username:<br>            error = &#39;Username is required.&#39;<br>        elif not password:<br>            error = &#39;Password is required.&#39;<br>        elif db.execute(<br>            &#39;SELECT id FROM user WHERE username = ?&#39;, (username,)<br>        ).fetchone() is not None:<br>            error = &#39;User {} is already \<br>                   registered.&#39;.format(username)</pre><pre>        if error is None:<br>            db.execute(<br>                &#39;INSERT INTO user (username, password) VALUES \<br>               (?, ?)&#39;, (username, <strong>generate_password_hash</strong>(password))<br>            )<br>            db.commit()<br>            return redirect(url_for(&#39;login&#39;))</pre><pre>        <strong>flash</strong>(error)</pre><pre>   return render_template(&#39;register.html&#39;)</pre><p>So far, we flash out various errors for the last three scenarios, but the errors have nowhere to go. If you launch your app now, you won’t see any errors being given when you attempt to register without a password.</p><h4><strong>Template (base.html)</strong></h4><p>To show the flashed errors to users when necessary, we need to make further updates to the templates. We can only make updates to register.html, but we may encounter similar scenarios when we deal with login view functions.</p><p>A better solution is to update the base template, which is extended by both register.html and login.html. The following is the error block I will include in base.html:</p><pre>{% for message in get_flashed_messages() %}<br>    &lt;div class=&quot;container alert alert-danger&quot;&gt;<br>      &lt;span&gt;Error: {{ message }}&lt;/span&gt;<br>    &lt;/div&gt;<br>{% endfor %}</pre><p>Same as before, I referred to the <a href="https://getbootstrap.com/docs/3.4/components/#glyphicons-examples">documentation of Bootstrap</a> on how to style the error information. It will render this effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dv7LuOCczjtk08oIKTa6cQ.png" /></figure><h3>Testing</h3><p>To test our registration component, let’s add another class and revise our app.test.py:</p><pre>import os<br>import unittest<br>import tempfile</pre><pre>import app</pre><pre>// ... </pre><pre>class FlaskrTestCase(unittest.TestCase):<br>  # set up a new temp database for per test<br>  def setUp(self):<br>    self.db_fd, app.app.config[&#39;DATABASE&#39;] = tempfile.mkstemp()<br>    app.app.config[&#39;TESTING&#39;] = True<br>    self.app = app.app.test_client()<br>    app.init_db()</pre><pre>  # destroy the temp database for per test<br>  def tearDown(self):<br>    os.close(self.db_fd)<br>    os.unlink(app.app.config[&#39;DATABASE&#39;])</pre><pre>  def register(self, username, password):<br>    return self.app.post(&#39;/register&#39;, data=dict(<br>      username=username,<br>      password=password<br>    ), follow_redirects=True)</pre><pre>  # test messages<br>  def test_register_messages(self):<br>    &quot;&quot;&quot;Test register messages using helper functions.&quot;&quot;&quot;<br>    rv = self.register(<br>            &quot;<a href="/service/mailto:cat@123.com">cat@123.com</a>&quot;,<br>            &quot;&quot;<br>    )<br>    assert b&#39;Password is required&#39; in rv.data</pre><pre>    rv = self.register(<br>            &quot;&quot;,<br>            &quot;123&quot;<br>    )<br>    assert b&#39;Username is required&#39; in rv.data</pre><p>With everything for the registration set up, don’t forget to push your code to GitHub.</p><p>As our app.py is getting increasingly bloated, we will refactor its code to different .py files and start exploring using the recommended practice in developing Flask applications, factories, or blueprints, in the next tutorial, plus the log-in component.</p><h3>Tutorial List</h3><ul><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115">Build and test a mini Flask application</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760">Build, Test, and Deploy a Flask Application: Part 1 — Templates</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc">Build, Test, and Deploy a Flask Application: Part 2 — Authentication</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21">Build, Test, and Deploy a Flask Application: Part 3 — Application Factory and Blueprints</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb">Build, Test, and Deploy a Flask Application: Part 4 — Restructuring Testing</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e">Build, Test, and Deploy a Flask Application: Part 5 — Authentication (continued)</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a">Build, Test, and Deploy a Flask Application: Part 6 — Review System</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-7-60dde9080330">Build, Test, and Deploy a Flask Application: Part 7 — Deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53f2c8df3ebc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc">Build, Test, and Deploy a Flask Application — Part 2</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build, Test, and Deploy a Flask Application: Part 1]]></title>
            <link>https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/53a7b0cbe760</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 06:04:17 GMT</pubDate>
            <atom:updated>2019-12-28T18:49:58.427Z</atom:updated>
            <content:encoded><![CDATA[<h4>Templates in Flask</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8RQ5vx_MUvg--Bng" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks.org</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Meta Information About This Tutorial</h3><h4>Learning goals</h4><ul><li>Understand templates in Flask</li></ul><p>Note: This tutorial is part of the series <a href="https://medium.com/@neohao/learn-flask-in-a-scientific-way-baf4d8055f6e"><em>Learn Flask in a scientific way</em></a><em>.</em></p><h4>Source code</h4><ul><li>The source code of this tutorial can be accessed on <a href="https://github.com/Neo-Hao/mean-review-collector">GitHub</a>.</li><li>The demo can be accessed at <a href="https://pacific-fortress-91193.herokuapp.com/">https://pacific-fortress-91193.herokuapp.com/</a>.</li><li>The version that covers only this tutorial can be accessed <a href="https://github.com/Neo-Hao/mean-review-collector/tree/816e41c65f77a62eb97ddb0db0377c60771b9304">here</a>.</li></ul><h3>Planning and Design</h3><p>Before we start building our application, we have to make a good plan. Our application at least needs seven pages to work:</p><ul><li>Homepage: Present a list of mean reviews from different contributors.</li><li>About page: Introduce our service.</li><li>404 page: When visitors request a page that doesn’t exist.</li><li>Register an account page: Allows people to register an account.</li><li>Login page: Allows users to log in.</li><li>Add a review page: Allows users to add a review (require login).</li><li>Update a review page: Allows users to update a review (require login).</li></ul><p>Both “add a review page” and “update a review page” require user authentication first. To be succinct, we will leave these two pages out in our part 1 tutorial.</p><h3>Project Setup</h3><p>Here we will assume that you have installed Flask and <a href="https://docs.python.org/3/library/venv.html">venv</a>, and understand their basic usage. If not, please read <a href="https://medium.com/better-programming/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115"><em>Build and Test a Mini Flask Application</em></a> first.</p><ol><li>Create an empty repository named flask-app on GitHub and download it to the local environment (and navigate to the downloaded empty folder through the command line).</li></ol><pre>git clone https://github.com/<em>your-username</em>/mean-review-collector<br>cd mean-review-collector</pre><p>2. Create a virtual environment in the downloaded, empty folder:</p><pre>python3 -m venv env<br>source env/bin/activate</pre><h3>Getting Started</h3><p>Based on what we learned from <a href="https://medium.com/better-programming/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115"><em>Build and Test a Mini Flask Application</em></a>, we need at least two Python files for this application:</p><ul><li>app.py: This is where the logic of our application lives; app handles all the routing and view functions.</li></ul><pre>from flask import Flask, make_response</pre><pre>app = Flask(__name__)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&#39;)<br>def home():<br>    return &#39;home page&#39;</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/about&#39;)<br>def about():<br>    return &#39;about page&#39;</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/register&#39;)<br>def register():<br>    return &#39;register page&#39;</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/login&#39;)<br>def login():<br>    return &#39;login page&#39;</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&lt;page_name&gt;&#39;)<br>def other_page(page_name):<br>    response = make_response(&#39;The page named %s does not exist.&#39; \<br>                            % page_name, 404)<br>    return response</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><ul><li>app.test.py: This is where the testing of the above route and view functions happens.</li></ul><pre>import unittest</pre><pre>from app import app</pre><pre>class BasicTestCase(unittest.TestCase):</pre><pre>def test_home(self):<br>        tester = app.test_client(self)<br>        pages = [&#39;/&#39;, &#39;about&#39;, &#39;register&#39;, &#39;login&#39;]<br>        for page in pages:<br>            response = tester.get(page, content_type=&#39;html/text&#39;)<br>            self.assertEqual(response.status_code, 200)</pre><pre>def test_other(self):<br>        tester = app.test_client(self)<br>        response = tester.get(&#39;test&#39;, content_type=&#39;html/text&#39;)<br>        self.assertEqual(response.status_code, 404)</pre><pre>if __name__ == &#39;__main__&#39;:<br>    unittest.main()</pre><p>Even if all testing cases are passed, you will not have the intended effects rendered per page (when you check them through your browser), and you also lack a navigation bar.</p><p>To achieve such effects, you will need help from templates in Flask.</p><h3>Templates</h3><p>Templates in Flask are tools that manage presentation logic. Part of the content in each template is HTML code, while the other is logic (e.g., determine whether to show a page to unauthenticated users).</p><p>Flask uses <a href="https://jinja.palletsprojects.com/">Jinja 2</a> as the template engine to manage such logic. In its simplest form, a Jinja 2 template is just a file that contains static HTML code:</p><pre>&lt;h1&gt;Hello world!&lt;/h1&gt;</pre><p>In a more complex form, a Jinja 2 template can just be a file that contains HTML code, variables, and logic to achieve various purposes.</p><p>For instance, the following code renders different text depending on if a visitor is authenticated:</p><pre>{% if user %}  <br>   &lt;h1&gt;Hello, {{ username }}! &lt;/h1&gt;<br>{% else %}  <br>   &lt;h1&gt;Hello, Stranger! &lt;/h1&gt;<br>{% endif %}</pre><p>{{ … }} contains the variable name if you need to mix HTML with variables (in Python code).</p><p>{% … %} contains logic (such as conditional execution or loops). What goes inside it is basically Python code, as Jinja 2 is purely Python. The concept of opening and closing brackets applies here.</p><p>In other words, each opening {%…%} needs to be closed at the end with another {%…%}.</p><p>For a Flask application, all templates live under a folder named “templates” (for Flask to recognize them as templates). In other words, your Flask application will have the following structure when you extend it to include templates for each of the planned pages:</p><pre>--- app.py<br>--- app.test.py<br>--- templates<br>       --- home.html<br>       --- about.html<br>       --- register.html<br>       --- login.html<br>       --- 404.html</pre><p><em>Beyond the syntax, it is important to understand the extendability of templates.</em></p><p>Web pages of the same application may share certain elements. For instance, we want our five pages to share exactly the same navigation bar.</p><p>In this case, we can carve out the common elements and put them in a different HTML file (base file), and let other HTML files extend the base file.</p><p>In our case, we call this base file base.html and place it under the templates folder. The structure of our application will be:</p><pre>--- app.py<br>--- app.test.py<br>--- templates<br>       --- home.html<br>       --- about.html<br>       --- register.html<br>       --- login.html<br>       --- 404.html<br>       --- base.html</pre><p>The base template contains:</p><pre>&lt;!doctype html&gt;<br>&lt;nav&gt;<br>  &lt;h1&gt;Mean Review Collector&lt;/h1&gt;<br>  &lt;ul&gt;<br>    &lt;li&gt;&lt;a href=&quot;{{ url_for(&#39;home&#39;) }}&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;{{ url_for(&#39;about&#39;) }}&quot;&gt;About&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;{{ url_for(&#39;register&#39;) }}&quot;&gt;Register&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;{{ url_for(&#39;login&#39;) }}&quot;&gt;Login&lt;/a&gt;&lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/nav&gt;<br>&lt;section class=&quot;content&quot;&gt;<br>  &lt;header&gt;<br>    {% block header %}{% endblock %}<br>  &lt;/header&gt;<br>  {% block content %}{% endblock %}<br>&lt;/section&gt;</pre><p><a href="https://flask.palletsprojects.com/en/1.1.x/api/#flask.url_for">url_for</a> is a Flask method that generates a URL for the given endpoint.</p><p>For instance, url_for(‘home’) will return the URL for the home page. There are four links in our navigation bar (no bar so far), and that’s all this file contains. The section block is to define which structure other templates that extend base should follow — to have both a header and content blocks.</p><p>For instance, the template of our home page will extend base:</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% block header %}<br>  &lt;h1&gt;{% block title %}Mean Reviews{% endblock %}&lt;/h1&gt;<br>{% endblock %}</pre><pre>{% block content %}<br>  &lt;blockquote&gt;<br>    This paper is more appropriate for a speciality journal. Like, <br>    one that specializes in terrible papers. - From <a href="http://twitter.com/thirdreviewer">@thirdreviewer</a><br>  &lt;/blockquote&gt;<br>  &lt;blockquote&gt;<br>    Before I can recommend acceptance, I request the following 272 <br>    changes to the manuscript. - From <a href="http://twitter.com/thirdreviewer">@thirdreviewer</a><br>  &lt;/blockquote&gt;<br>  &lt;blockquote&gt;<br>    Let me begin by apologizing for being so late with this review – <br>    it took me much longer than expected to figure out how best to <br>    insult all the authors. - From <a href="http://twitter.com/thirdreviewer">@thirdreviewer</a><br>  &lt;/blockquote&gt;<br>{% endblock %}</pre><p>The first line {% extends ‘base.html’ %} indicates the extension.</p><p>The following sections follow the structure set by the base template and are filled up with three mean reviews. To render this template, we need to update our code in app.py:</p><pre>from flask import Flask, render_template, make_response</pre><pre>app = Flask(__name__)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&#39;)<br>def home():<br>    return render_template(&#39;home.html&#39;)</pre><pre>// more</pre><p>We import the <a href="https://flask.palletsprojects.com/en/1.1.x/api/#flask.render_template">render_template</a> method, so we can use it in our return statement to render the effects defined in our templates. When this method takes one parameter, the parameter has to be the template name.</p><p>Let’s launch the app:</p><pre>python3 app.py</pre><p>You will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*dNEo_WyMK11r-BuM_dNtgA.png" /></figure><p>The other templates extend the base template as well. To check what their code looks like, please refer to this page on <a href="https://github.com/Neo-Hao/mean-review-collector/tree/6ac5d30e8db109dd75f4f1dd3b5aecd7fe6407c9">GitHub</a>. The app.py also needs to be updated:</p><pre>from flask import Flask, render_template, make_response</pre><pre>app = Flask(__name__)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&#39;)<br>def home():<br>    return render_template(&#39;home.html&#39;)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/about&#39;)<br>def about():<br>    return render_template(&#39;about.html&#39;)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/register&#39;)<br>def register():<br>    return render_template(&#39;register.html&#39;)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/login&#39;)<br>def login():<br>    return render_template(&#39;login.html&#39;)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&lt;page_name&gt;&#39;)<br>def other_page(page_name):<br>    response = make_response(render_template(&#39;404.html&#39;), 404)<br>    return response</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>So far, we have implemented all the templates and a functioning navigation bar (not a bar yet). We still miss the style for this application.</p><h3>Add Styles</h3><p>To add styles to our application, we will use <a href="https://getbootstrap.com/">Bootstrap</a> instead of writing our CSS file.</p><p>Bootstrap is an open-source framework from Twitter that helps you build webpages that are attractive and also compatible with all modern browsers. For more information about Bootstrap, see <a href="https://getbootstrap.com/">getbootstrap.com</a>.</p><p>To add Bootstrap style to your base template, you simply need to add the following to the beginning of your base template (<a href="https://getbootstrap.com/docs/4.3/getting-started/introduction/">see the quick start instruction here</a>):</p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;<a href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css</a>&quot; integrity=&quot;sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T&quot; crossorigin=&quot;anonymous&quot;&gt;<br>&lt;script src=&quot;<a href="https://code.jquery.com/jquery-3.3.1.slim.min.js">https://code.jquery.com/jquery-3.3.1.slim.min.js</a>&quot; integrity=&quot;sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;<a href="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js">https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js</a>&quot; integrity=&quot;sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;<a href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js">https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js</a>&quot; integrity=&quot;sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;</pre><p>After that, you need to make several changes to your template files. For instance, your HTML code for the first quote will change from:</p><pre>&lt;blockquote&gt;<br>    This paper is more appropriate ... in terrible papers. -From <br>    @thirdreviewer<br>&lt;/blockquote&gt;</pre><p>To this:</p><pre>&lt;blockquote class=&quot;blockquote&quot;&gt;<br>    &lt;p class=&quot;mb-0&quot;&gt;This paper is more appropriate ... in terrible <br>                    papers.&lt;/p&gt;<br>    &lt;footer class=&quot;blockquote-footer&quot;&gt;From @thirdreviewer&lt;/footer&gt;<br>&lt;/blockquote&gt;</pre><p>There is no point in memorizing anything here. All you need to do is to refer to <a href="https://getbootstrap.com/docs/4.0/getting-started/introduction/">the documentation of Bootstrap</a> and search for what you need carefully.</p><p>In the above case, I searched for <a href="https://getbootstrap.com/docs/4.0/content/typography/#blockquotes">blockquotes</a>. The code of all the updated templates can be found on <a href="https://github.com/Neo-Hao/mean-review-collector">GitHub</a>. When you launch the application again, you will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHzQxtXpMb-1t-4dAcBdAg.png" /></figure><p>Bootstrap makes our style adaptable to different sizes of screens. On mobile phones, tablets, or smaller screens, our application will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*eM27_e_cJ4sh9_SFv_3KlA.png" /></figure><p>Now you have successfully styled your Flask application. Don’t forget to push your code to GitHub.</p><p>This completes our second tutorial of <a href="https://medium.com/@neohao/learn-flask-in-a-scientific-way-baf4d8055f6e">Learn Flask in a scientific way</a>.</p><h3>Tutorial List</h3><ul><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115">Build and test a mini Flask application</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760">Build, Test, and Deploy a Flask Application: Part 1 — Templates</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc">Build, Test, and Deploy a Flask Application: Part 2 — Authentication</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21">Build, Test, and Deploy a Flask Application: Part 3 — Application Factory and Blueprints</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb">Build, Test, and Deploy a Flask Application: Part 4 — Restructuring Testing</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e">Build, Test, and Deploy a Flask Application: Part 5 — Authentication (continued)</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a">Build, Test, and Deploy a Flask Application: Part 6 — Review System</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-7-60dde9080330">Build, Test, and Deploy a Flask Application: Part 7 — Deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a7b0cbe760" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760">Build, Test, and Deploy a Flask Application: Part 1</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Flask in a scientific way]]></title>
            <link>https://medium.com/@hoppa-digital/learn-flask-in-a-scientific-way-baf4d8055f6e?source=rss-eec8759fb141------2</link>
            <guid isPermaLink="false">https://medium.com/p/baf4d8055f6e</guid>
            <category><![CDATA[effective-learning]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Hoppa Digital]]></dc:creator>
            <pubDate>Tue, 12 Nov 2019 06:30:27 GMT</pubDate>
            <atom:updated>2019-12-28T18:49:27.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ynA-S12sUFgij_FOEseBDQ.png" /></figure><p>Since I started working as a faculty two years ago, I spent more time writing papers than code. For a research project that I started a few months ago, my students and I had to pick a framework that can support fast prototyping and can also be learned given a month or two. Eventually, we picked Flask, spent time learning it, and used it to develop our intended product. The project is still ongoing and moving on smoothly.</p><p>Same as others, when I had to learn Flask, I went over a set of different tutorials other developers put online, and read a couple of books. The qualities of tutorials and books vary. Most tutorials carry a lot of assumptions about their readers but never laid those assumptions out clearly. Many tutorials presented too much information in a very short time, which is likely to overload learners cognitively. It takes a lot for learners, especially the novices, to overcome all these barriers to achieve effective learning. Reflecting on my still fresh learning experience, I want to write a series of tutorials that cover learning Flask in a more task-oriented and learner-centered way.</p><h3>Development goals</h3><p>We are going to develop a web application that allows scientists to post mean reviews they received for their papers, and check all mean reviews posted by other scientists.</p><p>This can potentially be a good venue to release the pressure they gain from academic life. The end product may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydX83x7tyNIHIQOrCC-Exg.png" /></figure><h3>Assumptions about learners</h3><ul><li>Have some exposure to programming in Python.</li><li>Have some knowledge of object-oriented programming.</li><li>Know a little bit about Git.</li><li>Have some knowledge of HTML and CSS.</li><li>Have some knowledge of the basic structure of a Flask web application, and what “requests” and “responses” are in Flask. (<em>Covered in </em><a href="https://medium.com/better-programming/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115"><em>Build and Test a Mini Flask Application</em></a><em>.</em>)</li></ul><h3>Source code and demo</h3><ul><li>The source code of this tutorial can be accessed on <a href="https://github.com/Neo-Hao/mean-review-collector">GitHub</a>.</li><li>The demo application can be accessed at <a href="https://pacific-fortress-91193.herokuapp.com/">https://pacific-fortress-91193.herokuapp.com/</a>.</li></ul><h3>Tutorial List</h3><ul><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-mini-flask-application-1d9ca6c45115">Build and test a mini Flask application</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-an-interactive-flask-application-part-i-templates-53a7b0cbe760">Build, Test, and Deploy a Flask Application: Part 1 — Templates</a></li><li><a href="https://medium.com/better-programming/build-test-and-deploy-a-flask-application-part-2-53f2c8df3ebc">Build, Test, and Deploy a Flask Application: Part 2 — Authentication</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-3-3a2abfe4be21">Build, Test, and Deploy a Flask Application: Part 3 — Application Factory and Blueprints</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-4-5aa4f079fadb">Build, Test, and Deploy a Flask Application: Part 4 — Restructuring Testing</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-5-4a3c0bc36b8e">Build, Test, and Deploy a Flask Application: Part 5 — Authentication (continued)</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-6-952a1b29a02a">Build, Test, and Deploy a Flask Application: Part 6 — Review System</a></li><li><a href="https://medium.com/@neohao/build-test-and-deploy-a-flask-application-part-7-60dde9080330">Build, Test, and Deploy a Flask Application: Part 7 — Deployment</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baf4d8055f6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>