Django
Protection is on by default. Add the {% csrf_token %} tag to every POST form, otherwise the server responds with error 403.
A template is HTML with places for data. A form is a way to get data from the user. We look at both; examples with a “Run” button execute right in the browser.
Flask uses Jinja, and Django's template language is very similar to it.
{{ value }} outputs data and escapes HTML automatically.{% if %} and {% for %} add conditions and loops.{% extends %} and {% block %} give all pages a shared frame.from flask import Flask, render_template_string
app = Flask(__name__)
PAGE = """
<h1>Tasks: {{ tasks|length }}</h1>
{% for task in tasks %}
<p>{{ loop.index }}. {{ task.title }}{% if task.done %} (done){% endif %}</p>
{% else %}
<p>No tasks yet</p>
{% endfor %}
"""
@app.route("/")
def index():
tasks = [
{"title": "Buy a racket", "done": True},
{"title": "Read about templates", "done": False},
]
return render_template_string(PAGE, tasks=tasks)
print(app.test_client().get("/").text)
test_client() sends a request to the app without a real server. Tests are written the same way.
The header and footer are described once, and pages replace only their own block.
<!doctype html>
<html lang="en">
<head><title>{% block title %}Site{% endblock %}</title></head>
<body>
<nav><a href="/">Home</a></nav>
{% block content %}{% endblock %}
</body>
</html>
{% extends "base.html" %}
{% block title %}Tasks{% endblock %}
{% block content %}
<h1>My tasks</h1>
{% endblock %}
In Flask the files live in the templates folder, and render_template("index.html") returns the page. In Django render(request, "index.html") does the same.
If you output the user's text as it is, they can put their own script on the page. This is called XSS.
from flask import Flask, render_template_string, request
app = Flask(__name__)
@app.route("/")
def index():
name = request.args.get("name", "guest")
safe = render_template_string("<p>{{ name }}</p>", name=name)
danger = render_template_string("<p>{{ name|safe }}</p>", name=name)
return f"Correct: {safe}\nDangerous: {danger}"
response = app.test_client().get("/", query_string={"name": "<script>alert(1)</script>"})
print(response.text)
The |safe filter turns the protection off. Use it only for HTML you wrote yourself.
Form data is in request.form. The server must check it itself: checks in the browser are easy to bypass.
from flask import Flask, redirect, render_template_string, request, url_for
app = Flask(__name__)
tasks = []
PAGE = """
{% if error %}<p>{{ error }}</p>{% endif %}
<form method="post"><input name="title"><button>Add</button></form>
<ul>{% for task in tasks %}<li>{{ task }}</li>{% endfor %}</ul>
"""
@app.route("/", methods=["GET", "POST"])
def index():
error = None
if request.method == "POST":
title = request.form.get("title", "").strip()
if not title:
error = "Enter a title"
elif len(title) > 100:
error = "Title is too long"
else:
tasks.append(title)
return redirect(url_for("index"))
return render_template_string(PAGE, tasks=tasks, error=error)
client = app.test_client()
print("Empty form:", "Enter a title" in client.post("/", data={"title": " "}).text)
response = client.post("/", data={"title": "First task"})
print("Status after adding:", response.status_code, "redirect to", response.location)
print("Tasks:", tasks)
After a successful POST, send a redirect. Otherwise, when the page is refreshed, the browser repeats the submission and the task is added again.
Another site can quietly submit a form on behalf of a logged-in user. The defence is a secret token in every form.
Protection is on by default. Add the {% csrf_token %} tag to every POST form, otherwise the server responds with error 403.
There is no built-in protection. The usual choice is the Flask-WTF extension: CSRFProtect(app) and a hidden token field in the form.
A form class describes the fields, checks the data and can render itself as HTML.
from django import forms
class TaskForm(forms.Form):
title = forms.CharField(label="Task", max_length=100)
from django.shortcuts import redirect, render
from .forms import TaskForm
from .models import Task
def index(request):
form = TaskForm(request.POST or None)
if form.is_valid():
Task.objects.create(title=form.cleaned_data["title"])
return redirect("index")
return render(request, "index.html", {"form": form, "tasks": Task.objects.all()})
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button>Add</button>
</form>
Links checked on .
We have forms; now let us learn to recognise the user.