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.
Topic: Python for AI & Automation in AI & Data · Course information
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?
- How Do HTTP Methods and Responses Fit In?
- How Do Jinja Templates Work?
- How Do You Handle Forms in Flask?
- How Should You Validate Input?
- How Can You Practise the Fundamentals?
- References
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.
| Converter | Accepts |
|---|---|
| string (default) | Any text without a slash |
| int | Positive integers |
| float | Positive floating point values |
| path | Text including slashes |
| uuid | UUID 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?
| Check | Example |
|---|---|
| Required | Name must not be empty |
| Type | Age must be an integer |
| Length | Message under 2,000 characters |
| Allow list | Country from a fixed list |
| Format | Email 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
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Wow
0
Sad
0
Angry
0