Codeskill

Learn to code, step by step

Building a Simple Web Application with Flask

Building a simple web app with Flask. Setup, routes, templates, and a basic form.

What is Flask?

Flask is a lightweight Python web framework. It is a microframework – few dependencies, minimal boilerplate – which makes it a good fit for small to medium web apps.

Setting up Flask

You need Python installed. Then:

pip install Flask

Creating a Flask app

Create a file called app.py, import Flask, and define a route:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

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

What is going on:

  • Flask(__name__) creates the app instance.
  • @app.route('/') maps a URL to a function.
  • hello_world() returns the response text.
  • app.run(debug=True) starts the dev server and shows errors in the browser.

Running the app

From the folder containing app.py:

python app.py

Flask runs at http://127.0.0.1:5000/ by default. Open that in a browser and you should see “Hello, World!”.

Creating more views

Add routes by decorating more functions:

@app.route('/about')
def about():
    return 'About page'

That serves “About page” at http://127.0.0.1:5000/about.

Templates

For anything beyond a one-liner, use templates to separate logic from HTML. Flask uses Jinja2.

Create a templates folder and add index.html:

<!doctype html>
<html>
<head>
  <title>Hello from Flask</title>
</head>
<body>
  <h1>{{ message }}</h1>
</body>
</html>

Render it with render_template:

from flask import render_template

@app.route('/')
def home():
    return render_template('index.html', message="Hello from Flask")

The message variable appears inside the <h1> tag.

Adding interactivity with forms

Flask handles form submissions too. Install Flask-WTF if you want form helpers:

pip install Flask-WTF

Create form.html:

<form method="post" action="/submit">
    <input type="text" name="name" placeholder="Enter your name"/>
    <input type="submit" value="Submit"/>
</form>

Handle the POST in app.py:

from flask import request

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

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    return f'Hello {name}'

Visit http://127.0.0.1:5000/form, enter your name, submit, and Flask greets you by name.

That is a working Flask app: one route, a template, a form. From here you can add more pages, connect a database, or bolt on authentication as the project grows.

PreviousData Analysis Basics with Python’s Pandas Library