DEV Community

Medea
Medea

Posted on

Simple Flask App

Simple Flask App

Introduction

In this post I'll show you the code for a simple flask app which collects data in a form and gives it back to you.


Structure

Your files and folder needs to be structured like below:

-- main.py
-- templates
   |__ index.html
Enter fullscreen mode Exit fullscreen mode

Code

main.py

from flask import Flask, request, redirect, render_template
app = Flask(__name__)

@app.route('/')
def index():
  return render_template("index.html")

@app.route("/form", methods=['GET', 'POST'])
def form():
  if request.method == 'POST':
    fname = request.form['fname']
    lname = request.form['lname']
    return f"Your full name is {fname} {lname}"
  else:
    return redirect("/")

app.run(host='0.0.0.0', port=8080)
Enter fullscreen mode Exit fullscreen mode

templates/index.html

<!DOCTYPE html>
<html lang="en-GB">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Simple Flask App</title>
  </head>
  <body>
    <h1>Simple Flask App</h1>
    <form method="POST" action="/form">
      <input placeholder="first name" name="fname" autocomplete="off" required><br>
      <input placeholder="last name" name="lname" autocomplete="off" required><br>
      <button>submit</button>
    </form>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Looks

The website will look something like this:

Image description


Conclusion

After putting all of this code together, you will have a fully functional flask app!
Thanks for reading and if you want to view the code together, check it out here!

Discussion (0)