Processing of HTML Forms
Do you remember when earlier in the course we learned about HTML forms that send (usually POST-formatted) HTTP requests to the backend system? Let's now complement the equation by also building the backend side.
Simple Example
Let's start by creating a Flask application and defining a simple route that returns an HTML page with a form:
1from flask import Flask, render_template, request
2
3app = Flask(__name__)
4
5@app.route('/')
6def index():
7 return render_template('index.html')This route returns a template called 'index.html' which contains an HTML form. Let's create this template and add the form to it:
1<!DOCTYPE html><html><head><title>Flask form</title></head><body><h1> Send data to Flask</h1><form method="POST" action="/submit"> <label for="nimi">Name:</label><input type="text" id="nimi" name="nimi"><br><br> <label for="sukunimi">Last name:</label><input type="text" id="sukunimi" name="sukunimi"><br><br> <label for="email">E-mail:</label><input type="email" id="email" name="email"><br><br><input type="submit" value="send"></form></body></html>This form contains three fields: name, surname, and email. When the user submits the form, its data is sent with a POST request to the '/submit' route. Let's define this route in the Flask application and add code to handle the form data:
1@app.route('/submit', methods=['POST'])
2def submit():
3 name = request.form['name']
4 lastname = request.form['lastname']
5 email = request.form['email']
6 return f"Hello {name} {surname}, your email is {email}."Learn to hack — start here
Hundreds of interactive courses, virtual labs and CTF challenges in your browser. Start a free trial — no card required.