Python - Deploying a Web App with Flask
Setup
Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications.
pip install flask
Hello World
Flask expects you to put your HTML pages inside a folder templates
. Add a simple index.html
page and outside of this folder add a main.py
:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
app.run(host='192.168.2.112')
Visit localhost
or your servers IP address on Port 5000 to see the content of your HTML page.
Interacting with your HTML
Now we have a static website that is being served by Flask. But there is no interface between the web frontend and the Python backend. For this we have to create a POST Route in Flask that allows us to send data from the frontend to the backend:
@app.route('/', methods=['GET'])
def home_get():
return render_template('index.html')
@app.route('/', methods=['POST'])
def home_post():
return render_template('index.html')
Now we can add a Form Element to our website that can perform a Post Request to send the content of it's input fields to our Flask backend:
<form method="POST">
<div><input name="first"/></div>
<div><input name="sec"/></div>
<p><strong></strong></p>
<button>Multiply!</button>
</form>
So now - whenever the page is loaded we receive a GET request. But pressing the multiply button will send a POST request:
[10/Oct/2022 12:16:55] "GET / HTTP/1.1" 200 -
[10/Oct/2022 12:16:57] "POST / HTTP/1.1" 200 -
When we print(request.form)
inside home_post()
we can now see that we are receiving the values we put in to the frontend in our Flask backend:
ImmutableMultiDict([('first', '5'), ('second', '5')])
We can grab them from there and write them into variables:
def home_post():
# print(request.form)
val1 = request.form['first']
val2 = request.form['second']
return render_template('index.html')
And now we can manipulate them however we like and print the result:
result = float(val1) * float(val2)
print(result)
To output the result to the web frontend we can add JinJa variables:
<p>Result: <strong>{{result}}</strong></p>
And use the return statement of our function to return this value:
return render_template('index.html', result=result)