Flask Fundamentals from Scratch: Routing, Templates and Forms

Learning Flask from scratch means mastering three building blocks. Routing maps URLs to Python functions with the @app.route decorator, including variable parts such as /user/<name> and allowed HTTP methods. Templates use Jinja to render HTML, with a base layout that child pages extend, and autoescaping that protects against injected HTML.

May 17, 2025 - 10:45
Updated: 
101.1k

Python for AI & Automation in AI & Data · Course information

Flask Fundamentals from Scratch: Routing, Templates and Forms

Quick answer: Learning Flask from scratch means mastering three building blocks. Routing maps URLs to Python functions with the @app.route decorator, including variable parts such as /user/<name> and allowed HTTP methods. Templates use Jinja to render HTML, with a base layout that child pages extend, and autoescaping that protects against injected HTML. Forms send data that you read from request.form, validate on the server, then redirect after a successful POST. Once these three feel natural, databases, blueprints and APIs are simply extensions of the same request and response cycle.

Key takeaways

  • A route is a URL rule plus a view function that returns a response.
  • Use url_for to build links instead of hard-coding paths.
  • Jinja template inheritance keeps layouts in one file.
  • Always validate form input on the server, even with HTML checks.
  • Redirect after POST to avoid duplicate submissions.

Table of Contents

How Does Routing Work in Flask?

The Flask Quickstart shows that a route binds a URL to a function. Variable rules capture parts of the URL, and converters such as int enforce a type:

@app.route("/post/<int:post_id>")
def show_post(post_id):
    return f"Post {post_id}"

Flask relies on Werkzeug for URL matching. Use url_for("show_post", post_id=3) to generate links, so changing a URL rule does not break templates.

ConverterAccepts
string (default)Any text without a slash
intPositive integers
floatPositive floating point values
pathText including slashes
uuidUUID strings

How Do HTTP Methods and Responses Fit In?

By default a route only answers GET. Add methods=["GET", "POST"] when a page also receives forms. GET should only read data; POST changes it, as described in MDN's HTTP methods guide. A view can return a string, a template, a dictionary (sent as JSON), or a tuple with a status code. Use abort(404) for missing records and redirect() to send users elsewhere.

How Do Jinja Templates Work?

Flask looks for templates in a templates folder and renders them with render_template. The Jinja documentation explains the syntax: {{ value }} prints, {% for %} and {% if %} control flow, and {% extends %} with {% block %} creates inheritance.

{% extends "base.html" %}
{% block content %}
  <h1>{{ title }}</h1>
{% endblock %}

The Flask templating page notes that autoescaping is on for .html templates, so a user who types a script tag sees it as text instead of running it.

How Do You Handle Forms in Flask?

A typical form view checks the method, reads fields and redirects after success. This post, redirect, get (PRG) pattern stops a browser refresh from resubmitting the form:

@app.route("/contact", methods=["GET", "POST"])
def contact():
    if request.method == "POST":
        name = request.form.get("name", "").strip()
        if not name:
            flash("Name is required.")
        else:
            flash("Thanks!")
            return redirect(url_for("contact"))
    return render_template("contact.html")

flash() needs a SECRET_KEY because messages are stored in the session. For larger forms, Flask-WTF adds form classes, validators and CSRF tokens.

How Should You Validate Input?

CheckExample
RequiredName must not be empty
TypeAge must be an integer
LengthMessage under 2,000 characters
Allow listCountry from a fixed list
FormatEmail matches an expected pattern

HTML attributes like required are easy to bypass, so repeat every check on the server. The OWASP Input Validation Cheat Sheet recommends allow-list validation wherever possible.

How Can You Practise the Fundamentals?

Build a three-page site: a home page, a list page with variable routes and a contact form, all sharing one base template. Then follow the full sequence in what to learn in Flask, in order, and lock down your forms with Flask security essentials. For guided labs, ask about our Python web development training.

References

Frequently Asked Questions

A route is a URL rule attached to a view function with the @app.route decorator, and the function returns the response for that URL.

url_for builds links from the view name, so if you change a URL rule later your templates and redirects keep working.

A child template extends a base layout and fills named blocks, so headers, footers and menus live in one shared file.

Use request.form.get with the field name inside a view that accepts POST, then validate the value before using it.

After a successful POST the view redirects to a GET page, so refreshing the browser does not submit the same form twice.

Flashed messages are stored in the signed session cookie, and Flask needs SECRET_KEY to sign that cookie securely.

No. Browser checks can be skipped easily, so every rule must also be enforced in your Flask view on the server.

Not for tiny forms, but Flask-WTF saves effort on larger ones by adding form classes, validators and CSRF protection.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Vaishnavi

Vaishnavi is a skilled tech professional at the Ethical Hacking Training Institute in Pune, responsible for managing and optimizing the technical infrastructure that supports advanced cybersecurity education. With deep expertise in network security, backend operations, and system performance, she ensures that practical labs, online modules, and assessments run smoothly and securely. Her behind-the-scenes contributions play a vital role in delivering a seamless and secure learning experience for aspiring ethical hackers.