Flask is a framework that is widely used to create APIs in Python. It is a simple yet powerful web framework. Flask is designed to help us work efficiently with its ability to scale up to complex applications.
In this shot, we learn how to retrieve HTML data from a Flask application.
First, we need to run the commands below to install the required dependencies:
pip install pipenv
pipenv shell
pipenv install Flask
Let’s create a file and name it app.py
.
We get the HTML input
from the Form
using the request.form.get()
function. We pass the name of HTML input as an argument.
Let’s look at an example:
k38 = request.form.get('kubernetes')
ansible = request.form.get('playbook')
In the code above:
request.form.get('kubernetes')
takes the input as its parameter. In this case, the input is kubernetes
and is stored in a k38
variable.request.form.get('playbook')
takes the input as its parameter. In this case, the input is playbook
and is stored in the ansible
variable.from flask import Flask, request, render_templateapp = Flask(__name__)# Creating a route that has both GET and POST request methods@app.route('/', methods=['GET', 'POST'])def home():if request.method == 'POST':name = request.form.get('name')username = request.form.get('username')return f'{name}, your username is {username}'return render_template('home.html')# Initiating the applicationif __name__ == '__main__':# Running the application and leaving the debug mode ONapp.run(debug=True)
We create a folder and name it templates
.
Inside the templates
folder, we create a file and name it home.html
. Then, we add the following code.
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><form action="" method="post"><label for="name">Name:</label><input type="text" id="name" name="name" placeholder="name"><label for="username">Username:</label><input type="text" id="username" name="username" placeholder="username"><button type="submit">Submit</button></form></body></html>
In our terminal, we run the following command to start the web application:
python app.py
click==8.0.3 colorama==0.4.4 Flask==2.0.2 itsdangerous==2.0.1 Jinja2==3.0.3 MarkupSafe==2.0.1 Werkzeug==2.0.2