18 |
19 |
20 | {% endblock %}
21 |
22 |
23 |
--------------------------------------------------------------------------------
/routes.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, escape, render_template
2 | app = Flask(__name__)
3 |
4 | # Root path that returns home.html
5 | @app.route('/')
6 | def home():
7 | return render_template("home.html")
8 |
9 | # About page
10 | @app.route('/about')
11 | def about():
12 | return render_template("about.html")
13 |
14 | # Route that accepts a username(string) and returns it. You can use something similar
15 | # to fetch details of a username
16 | @app.route('/user/')
17 | def show_user_profile(username):
18 | # show the user profile for that user
19 | return 'User %s' % escape(username)
20 |
21 | @app.route('/userwithslash//')
22 | def show_user_profile_withslash(username):
23 | # show the user profile for that user
24 | return 'User %s' % escape(username)
25 |
26 | @app.route('/post/')
27 | def show_post(post_id):
28 | # show the post with the given id, the id is an integer
29 | return 'Post %d' % post_id
30 |
31 | @app.route('/path/')
32 | def show_subpath(subpath):
33 | # show the subpath after /path/
34 | return 'Subpath %s' % escape(subpath)
35 |
--------------------------------------------------------------------------------
/routes_port80.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, escape, render_template
2 | app = Flask(__name__)
3 |
4 | # Root path that returns home.html
5 | @app.route('/')
6 | def home():
7 | return render_template("home.html")
8 |
9 | # About page
10 | @app.route('/about')
11 | def about():
12 | return render_template("about.html")
13 |
14 | # Route that accepts a username(string) and returns it. You can use something similar
15 | # to fetch details of a username
16 | @app.route('/user/')
17 | def show_user_profile(username):
18 | # show the user profile for that user
19 | return 'User %s' % escape(username)
20 |
21 | @app.route('/userwithslash//')
22 | def show_user_profile_withslash(username):
23 | # show the user profile for that user
24 | return 'User With Slash %s' % escape(username)
25 |
26 | @app.route('/post/')
27 | def show_post(post_id):
28 | # show the post with the given id, the id is an integer
29 | return 'Post %d' % post_id
30 |
31 | @app.route('/path/')
32 | def show_subpath(subpath):
33 | # show the subpath after /path/
34 | return 'Subpath %s' % escape(subpath)
35 |
36 | if __name__ == "__main__":
37 | app.run(port="80", host="0.0.0.0")
38 |
--------------------------------------------------------------------------------
/templates/template.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Flask Parent Template
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
First Web App
22 |
28 |
29 |
30 |
31 | {% block content %}
32 | {% endblock %}
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Flask: Getting Started
2 | This repo is to help you in setting up a simple Flask app. Use this to understand the elements of a Flask app. This document contains of the following sections:
3 | 1. [Installation](#installation)
4 | 2. [Quickstart](#quickstart-hello-world)
5 | 3. [Simple FLASK_APP](#a-simple-flask_app)
6 | 4. [Simple FLASK_APP on port 80](#a-simple-flask_app-port-80)
7 | 5. [Intro to Web: Client-Server](#intro-to-web-client-server-model)
8 |
9 | ### Installation
10 | It's recommended to do this on a new EC2 instance. So do spin up a new one if you don't have one yet.
11 |
12 | The installation steps are mentioned below. All these are based on this [page](https://flask.palletsprojects.com/en/1.1.x/installation/#create-an-environment).
13 |
14 | * Clone this Github repo
15 | * `git clone https://github.com/InsightDataScience/flask-sample-app`
16 |
17 | * Access repo folder. Create Python Virtual Environment
18 | * `cd flask-sample-app`
19 | * `python3 -m venv venv`
20 | * If you are seeing an error, you may have to run `python3 -m venv venv --without-pip`
21 |
22 | * Activate Environment
23 | * `. venv/bin/activate`
24 |
25 | * Install flask
26 | * `pip install Flask`
27 |
28 | ### Quickstart: Hello World
29 | In the dir `flask-sample-app`, there is a file `hello.py`. We'll use this to setup a hello-world Flask app.
30 | * `export FLASK_APP=hello.py`
31 | * `flask run --host=0.0.0.0`
32 | * On a browser, type in `http://(your-EC2-public-IP):5000` in the location bar. You should see “Hello, World!” on your browser.
33 | * You may have to enable your EC2 Security-Group to have an inbound rule with `port:5000` and `source:anywhere`
34 |
35 |
36 | ### A simple FLASK_APP
37 |
38 | Now that you have a hello-world Flask app working, we can build a slightly more involved app. This app involves a few components a webapp usually would have. We'll use the file `routes.py`, instead of `hello.py`.
39 |
40 | * Stop the Flask hello-world app by issuing `ctrl-c`
41 | * `export FLASK_APP=routes.py`
42 | * `flask run --host=0.0.0.0`
43 |
44 | Reload your web browser with the same link you used before. You should see a page with a couple of links and buttons on it. This should demonstrate on how to use CSS and JS files that's associated with a webapp.
45 |
46 | ### A simple FLASK_APP (port 80)
47 | Now we will run Flask app on port 80 - the default HTTP port for any webpage request.
48 |
49 | **WARNING: This method should NOT be used in any other production environment. This is only a quick way to have your Flask app running on port 80 for Insight Project**
50 |
51 | * Switch to user `su`
52 | * `sudo su - `
53 |
54 | * Go to previous folder
55 | * `cd flask-sample-app`
56 |
57 | * `python3 -m venv venv`
58 | * If you are seeing an error, you may have to run `python3 -m venv venv --without-pip`
59 |
60 | * Activate Environment
61 | * `. venv/bin/activate`
62 |
63 | * Install flask. Previous install was done for user `ubuntu`. Now we'll have to do same for user `su`.
64 | * `pip install Flask`
65 |
66 | * `export FLASK_APP=routes_port80.py`
67 |
68 | * Run Flask app in background. This should
69 | * `nohup flask run --host=0.0.0.0 --port=80 &`
70 | * ensure to copy `&` from the above command. This takes Flask app to the background. [Read more](https://www.lifewire.com/multitasking-background-foreground-process-2180219)
71 | * check the file `nohup.out` for any errors.
72 |
73 | ### Intro to Web: client-server model
74 |
75 | Once you have this app working, take time to understand how a webapp works. Here's a good [intro](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works) on how web works. Essentially there are 2 parts:
76 | * **client-code**: Everything that's related to a webpage that appears in a web browser. In this case, client-code includes everything in folders `static`, and `templates`.
77 | * `templates` has only HTML source code.
78 | * `static` has all JavaScript and CSS code that's used by pages by `templates`.
79 | * **server-code**: Flask server that "serves" webpages. In this case, files `hello.py`, `routes.py`, and `routes_port80.py` represents server-code.
80 |
81 | `client-code` makes requests that are **served** by routes in `server-code`. Hence the name web-server.
82 |
83 | To see how client-server model works, we'll use the webpage to understand it better. Type some text in the textarea you see in the home-page. Click button 'Use Route'. You should see text printed on browser's [console](https://developers.google.com/web/tools/chrome-devtools/console).
84 |
85 | The following happened when you clicked button 'Use Route':
86 | * `(client)` In JavaScript file `windowScript`, user-input is stored in variable `userName`. This value is sent to server.
87 | * `(server)` In file `routes_port80`, user-input is received in variable `username` (line 17).
88 | * you should the user-input in flask-server file `nohup.out`. In short, what you typed in the webpage has appeared in Flask server!
89 | * `(server)` The same `username` is returned with "User" prefixed.
90 | * this operation is done by route `/user/`.
91 | * `(client)` Back in JavaScript file `windowScript`, the new string is received in variable `data`. This is printed on the console.
92 |
93 | The above steps demonstrates a very simple example of how data is sent between client and server. This should give you an idea of a simple webapp now.
94 |
--------------------------------------------------------------------------------
/static/js/jquery-3.4.1.min.js:
--------------------------------------------------------------------------------
1 | /*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */
2 | !function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"