Handle form input in Flask
Tags: python, flask, webdev
Published: 2023-07-16 05:35:32

Flask is an easy-to-use web framework that follows an MVC architecture to develop web applications. It is popular because it is very easy to use and flexible allowing rapid development.

This is a guide to making a basic frontend and sending the response to the Flask API ultimately saving it in a database.

## HTML Frontend

Let's begin by creating a simple frontend where our users can enter their name, age, and hobby. 

```
<!DOCTYPE html>
<html>
<head>
  <title>User Form</title>
</head>
<body>
  <h2>User Input Form</h2>
  <form action="/submit" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br><br>

    <label for="age">Age:</label>
    <input type="number" id="age" name="age" required><br><br>

    <label for="hobby">Hobby:</label>
    <input type="text" id="hobby" name="hobby" required><br><br>

    <input type="submit" value="Submit">
  </form>
</body>
</html>
```

It is a simple HTML form that submits to a route '/submit' and it contains three input tags in HTML that will help get the input from the user.

## Flask Backend

Now we shall begin writing our flask API where we will handle this request from frontend.

```
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/submit', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form['name']
        age = request.form['age']
        hobby = request.form['hobby']
      
        return 'User data saved successfully!'
    return render_template('index.html')

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

```

In this flask API, we have set the route information at the top of the method to '/submit' where the form is submitted and allowed the method to have to get and post requests both.

In the API, request.form can be used to access the values of the input tags in the form. The values are accessed by the value of the name attribute assigned in the input tag.

## Connect database

The last step is to save these values in a database table. Lets connect to a database and perform the insert operation.

```
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    age = db.Column(db.Integer)
    hobby = db.Column(db.String(100))

    def __init__(self, name, age, hobby):
        self.name = name
        self.age = age
        self.hobby = hobby

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form['name']
        age = request.form['age']
        hobby = request.form['hobby']
        user = User(name=name, age=age, hobby=hobby)
        db.session.add(user)
        db.session.commit()
        return 'User data saved successfully!'
    return render_template('index.html')

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

```

The User class has modeled as a table for our input request and our data is going to get saved in the SQL lite database. By this, we are done with making a full-stack application.