Flask Web Framework

How a request becomes a response in Flask, needed by the templating, REST and database chapters.

10 lessons · 39 past questions · 121 marks in the papers collected here

Open the interactive lessons →Flask Web Framework past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Start here: the Python and HTTP you need, from zero
  2. One request, one function, one response
  3. What a view may return
  4. Routes, stacked routes and the trailing slash
  5. Dynamic parts of a URL: placeholders and converters
  6. Building URLs with url_for
  7. Redirects
  8. Reading what the browser sent
  9. abort and error handlers
  10. Forms, frontend and backend validation

1. Start here: the Python and HTTP you need, from zero

A view is a Python function: a request calls it, and what it returns becomes the page.

the four Python ideas and the one HTTP picture every Flask question uses

The question this lesson answers. What is the smallest amount of Python and HTTP you need to read a Flask question? Four ideas, each used on the next pages: f-strings, dictionaries, return and the decorator line.

Try each idea in your head first. The code below prints three things. Cover the comments and predict them.

You do not need much Python for this course, but you need these four ideas exactly right, because every Flask question is a few lines of Python with a URL attached.

name = "MAD"
print(f"Hello {name}")      # Hello MAD

d = {"a": 1}
print(d.get("b"), d.get("b", 0))   # None 0

def f():
    x = 1
print(f())                   # None
Definition

A decorator is the line @something above a def. Python passes the function to something and keeps whatever comes back under the same name. @app.route("/v") records the function in Flask's route table and hands the same function back, so the function itself is unchanged.

Putting them together. Three views, three requests. Watch which function runs and what leaves the server.

One HTTP request, in parts

PartExampleWho reads it in Flask
methodGET, POSTthe route's methods list
path/user/7the route rules
query string?tab=inforequest.args
bodyform fields or JSONrequest.form, request.json
status code (in the reply)200, 302, 404, 405, 500what the browser does next
Picture it

A request is a letter: the method is the kind of letter (asking or sending), the path is the address, the query string is a note on the envelope, and the body is what is inside. Flask reads the address first and only then opens the letter.

Worked example: What does this view send?

Problem.

@app.route("/hi/<name>") above def hi(name): return f"Hi {name}!". Request: GET /hi/Asha.

Idea.

The path fills name; the f-string builds the text.

  1. /hi/Asha matches with name = "Asha".
  2. The view returns "Hi Asha!".
  3. A string return is sent with 200.

Answer.

200, Hi Asha!

Common mistake.

Expecting the braces to appear: in an f-string, {name} is replaced by its value.

Worked example: A view that forgets to return

Problem.

@app.route("/x") above def x(): msg = "done".

Idea.

No return → None → not a valid response.

  1. The view runs and finishes without return.
  2. It gives back None.
  3. Flask cannot build a page from None: 500.

Answer.

500 Internal Server Error

Common mistake.

Expecting "done": a variable is not sent unless the function returns it.

One request in Flask: request arrives, then method and path choose a route, then view function runs, then return value becomes the reply

How to answer

StepDo this
1Match the method and path to a route.
2Take values from the path, the query string or the body.
3Run the function line by line.
4What it returns is the response body.

Worked example: Zero is still a value

Problem.

With d = {"n": 0}, what do d.get("n", 5) and d.get("m", 5) give?

Idea.

The default is used only when the key is missing.

  1. The key n exists, with value 0.
  2. So the first call gives 0.
  3. The key m is missing.
  4. So the second call gives 5.

Answer.

0 and 5.

Common mistake.

Thinking the default replaces a value that counts as false.

Worked example: Text from the address

Problem.

A route is /twice/<n> and the view returns n * 2. What is the reply to /twice/7?

Idea.

Without a converter the value is text.

  1. <n> has no converter, so n is the string "7".
  2. A string times 2 repeats it.
  3. The reply is 77.

Answer.

77

Common mistake.

Answering 14, which needs <int:n>.

Check your answer in ten seconds

Look for int: in the route before doing arithmetic.

The last two lines of almost every app. Python sets the variable __name__ for each file. When you run the file directly, its value is the text "__main__". When another file imports it, the value is the module's name.

Start the server only on a direct run

from flask import Flask

app = Flask(__name__)

if __name__ == "__main__":
    app.run(debug=True)
How the file app.py is used__name__Does app.run execute?
python app.py"__main__"yes: the server starts
import app inside another file"app"no

With no arguments app.run() serves on http://127.0.0.1:5000, which is the same machine as localhost:5000. debug=True restarts the server when the code changes and shows a detailed error page. Use it only while developing.

Memory line

The path picks the function; the return value is the reply.

2. One request, one function, one response

Flask reads the URL, runs the matching function, and sends back what it returns.

what Flask does between the browser's request and the page you see

The question this lesson answers. Between typing an address and seeing a page, what happens, and where can it fail? Two checks stand before your function: does a path match, and is the method allowed?

When you open http://127.0.0.1:5000/ the browser sends an HTTP request to the program listening on port 5000 of your own computer. That program is your Flask app. A request carries a method (usually GET) and a path (here /).

Picture it

Flask is a waiter with a menu. The menu lists dishes (paths) and the cook who makes each one (a view function). The waiter takes your order, gives it to that one cook, and brings back whatever the cook hands over. The analogy breaks in one place: if the cook hands back nothing, the waiter does not improvise; you get an error.

Definitions

A route is a rule that connects a URL path to a function, written @app.route("/path") above the function. That function is a view function. Its return value becomes the response body, and Flask adds a status code (200 when all is well).

app.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, MAD 1!"

app.run(debug=True)

Watch the two checks. The same two routes, four requests.

What travels each way

Request (browser → Flask)Response (Flask → browser)
method: GET, POST and othersstatus code: 200, 302, 404 and others
path: /user/7headers, such as Content-Type
query string: ?tab=infobody: the HTML or JSON you returned
body (for POST): form fields or JSON

Worked example: Two URLs against one route

Problem.

Using app.py above, what does the browser show for http://127.0.0.1:5000/ and for http://127.0.0.1:5000/about?

Idea.

Find the rule for each path; only then run the function.

  1. The route table has one rule: / → home.
  2. / matches, so home() runs and returns Hello, MAD 1!: status 200.
  3. /about matches no rule, so no function runs: Flask sends its Not Found page, status 404.

Answer.

/ shows Hello, MAD 1! (200); /about shows Not Found (404)

Common mistake.

Thinking home() runs for every URL because it is the only function.

Worked example: Paths are case-sensitive

Problem.

An app has @app.route("/hello") above def hello(): name = "MAD"; return f"<h1>Hello {name}</h1>". What do /hello and /Hello give?

Idea.

Paths are compared exactly, letter case included.

  1. /hello matches the rule exactly: the function runs.
  2. It returns the HTML <h1>Hello MAD</h1>, so the browser shows Hello MAD as a heading, status 200.
  3. /Hello has a capital H, so it is a different path: no rule matches and the result is 404.

Answer.

/hello: heading Hello MAD (200); /Hello: Not Found (404)

Common mistake.

Assuming URLs ignore case the way domain names do.

Notice

The browser shows the rendered HTML. A returned <h1>Hello MAD</h1> appears as the words Hello MAD in large type, not as the tags.

Exam tip

In every Flask question, write the route table first: one line per rule, path → function (methods). Most traps vanish once the table is on paper.

Which methods does a route answer? A rule written as @app.route("/") with no methods= list accepts GET. Flask adds two more on its own: HEAD (the same as GET but the body is left out, used to check a page exists) and OPTIONS ("which methods may I use here?"). Anything else, such as POST, gets 405 Method Not Allowed, because the path exists but not for that method.

One route, four methods

RequestStatusWhy
GET /200the default method of every route
HEAD /200 with an empty bodyadded by Flask for every GET route
OPTIONS /200added by Flask to report the allowed methods
POST /405the path matches but POST is not allowed

Worked example: 404 or 405?

Problem.

@app.route("/login", methods=["POST"]) is the only route. Requests: GET /login, POST /login, POST /logout.

Idea.

First match the path, then check the method.

  1. GET /login: the path matches, but only POST is allowed → 405.
  2. POST /login: path and method match → the view runs, 200.
  3. POST /logout: no rule has that path → 404 (the method never gets checked).

Answer.

405, 200, 404

Common mistake.

Answering 404 for GET /login: a wrong method on an existing path is 405, not 404.

Worked example: A query string on a plain route

Problem.

Only @app.route("/a") exists. What status does GET /a?x=1 get?

Idea.

Only the path is matched.

  1. The path is /a.
  2. The query string is not part of the match.

Answer.

200.

Common mistake.

Answering 404 because the rule has no x.

Memory line

No path: 404. Wrong method: 405. Both fine: your function.

Method for any exam question

StepDo this
1Write the route table: path, function, methods.
2Match the path exactly, including capital letters.
3Check the method.
4Only then run the view.

3. What a view may return

Strings make HTML, dicts and lists make JSON, tuples add a status, None is an error.

the kinds of values a view can return and the response each one makes

The question this lesson answers. What may a view hand back, and what does each choice become on the wire?

Every response carries a Content-Type header that tells the browser what the body is: text/html for a web page, application/json for JSON (a text format for data: objects in { } with quoted keys, lists in [ ]).

Return value → response (Flask 3.1)

The view returnsBodyStatusContent-Type
"text" or an HTML stringthe string200text/html
{"a": 1}{"a":1}200application/json
[1, 2][1,2]200application/json
("made", 201)made201text/html
redirect(...)short redirect page302text/html
None (or no return)error page500text/html
Picture it

The view is a parcel desk. Hand over a letter (a string) and it is posted as a page; hand over a form with boxes (a dict) and it is posted as JSON; staple a note with a number (a tuple) and that number is the status. Hand over nothing and the desk refuses: 500.

Worked example: A dict with a status

Problem.

A view ends with return {"user": "ana"}, 201. What does the client receive?

Idea.

The tuple's second item is the status; the dict becomes JSON.

  1. The first item is a dict, so Flask converts it to JSON: {"user":"ana"}.
  2. The second item, 201, becomes the status code.
  3. The Content-Type is application/json.

Answer.

{"user":"ana"}, status 201, JSON

Common mistake.

Expecting the Python repr with single quotes.

Worked example: A return inside a loop

Problem.

What does /signin?uid=bob&pwd=2 return?

Idea.

return ends the function, so the loop never reaches the second user.

  1. First iteration: u is ana. "ana" == "bob" is False, so the else branch runs.
  2. return "Unauthorized" ends the function on the first user.
  3. bob is never checked, even though his details match.

Answer.

Unauthorized

Common mistake.

Answering Authorized because bob is in the list.

Every shape a view may return. Flask builds the response from what you return. A string is the body; a dict or list becomes JSON; a tuple adds a status and/or headers. Anything else, such as a plain number, is an error (500).

Return shapes

ReturnStatusNotes
"made", 201201body plus status
"h", {"X-A": "1"}200body plus headers
"t", 202, {"X-B": "2"}202body, status, headers
[1, 2]200sent as JSON
5500an int is not a valid response

Worked example: Created

Problem.

A view ends with return {"id": 7}, 201.

Idea.

Dict → JSON; the second item is the status.

  1. The dict becomes a JSON body.
  2. 201 is used as the status.

Answer.

201, application/json

Common mistake.

Thinking the tuple is sent as a JSON array: Flask unpacks a tuple into body and status.

Worked example: A plain number

Problem.

What status does GET /count give?

Idea.

A number is not one of the accepted return types.

  1. The view returns the integer 5.
  2. Flask accepts text, dictionaries, lists, tuples and response objects.
  3. An integer raises a TypeError, which becomes a 500.

Answer.

500

Common mistake.

Expecting a page showing 5. Return str(5) for that.

Tips and tricks
  • Look for a path through the function that reaches no return. That path gives a 500.
  • Form values are strings: convert before doing arithmetic.
  • In a tuple the second item is the status code.
Memory line

Text is a page, a dictionary is JSON, nothing is a crash.

Method for any exam question

StepDo this
1Read the return line that actually runs.
2Name its type.
3Look for a status in a tuple.
4No return or an unsupported type means 500.

4. Routes, stacked routes and the trailing slash

Several rules can share a function; a final slash changes what matches.

how Flask decides whether a path matches a rule, including rules that end in /

The question this lesson answers. Does one extra / at the end change the result? Yes, and it behaves differently in each direction, which is why exams like it.

Flask does its URL matching with a library called Werkzeug (installed with Flask); the slash rules below are Werkzeug's. Each @app.route(...) line adds one rule to the route table. You may write several of them above the same function: each adds another path that runs that function. The order of the stacked lines does not matter for matching.

@app.route("/start")
@app.route("/begin")
def start():
    return "Let us begin"
Picture it

A trailing slash works like the difference between a folder and a file. /docs/ is a folder: if you leave the slash off, Flask politely sends you to the folder (a redirect). /about is a file: if you add a slash, there is no such folder, so it is Not Found.

The trailing-slash rules (Werkzeug 3.1)

Rule in the codeURL requestedResult
/about/about200
/about/about/404 Not Found
/docs//docs/200
/docs//docs308 redirect to /docs/, then 200
/home and /home/ both/home / /home/each goes to its own function

Worked example: Stacked routes

Problem.

With the start function above, what do /start, /begin and /stop return?

Idea.

Each stacked line is its own rule for the same function.

  1. Route table: /start → start, /begin → start.
  2. /start matches rule 1: Let us begin, 200.
  3. /begin matches rule 2: the same function runs: Let us begin, 200.
  4. /stop matches no rule: 404.

Answer.

Let us begin (200), Let us begin (200), Not Found (404)

Common mistake.

Thinking only the line nearest def counts.

Worked example: A folder-style rule

Problem.

@app.route("/menu/") returns "Menu". What happens for /menu, /menu/ and /menu/x?

Idea.

A rule ending in / redirects the slash-less URL to itself; extra segments match nothing.

  1. /menu/ matches exactly: Menu, 200.
  2. /menu is the same rule without its slash: Flask replies 308 with Location: /menu/.
  3. The browser follows the redirect, requests /menu/ and shows Menu.
  4. /menu/x has an extra segment that no rule has: 404.

Answer.

/menu → redirect, then Menu; /menu/ → Menu; /menu/x → Not Found

Common mistake.

Answering 404 for /menu.

Trap

Learn the table both ways round. The slash-less URL of a slashed rule is redirected; the slashed URL of a slash-less rule is 404.

Two rules, one path. Flask checks rules in the order they were registered. If two functions are both decorated with @app.route("/a"), the first one registered handles every request for /a; the second never runs and no error is shown.

Repeated rules versus repeated names

Same path on two functionsSame function name twice
Example@app.route("/a") def x and @app.route("/a") def y@app.route("/a") def x and @app.route("/b") def x
When it showsat request time: /a runs xat start-up: the app refuses to load
Resultthe first registered winsAssertionError: "View function mapping is overwriting an existing endpoint function: x"

Worked example: Which text does /a show?

Problem.

@app.route("/a") above def x(): return "x", then @app.route("/a") above def y(): return "y".

Idea.

Rules are tried in registration order; the first match wins.

  1. Both rules match /a.
  2. x was registered first.
  3. Its return value is the response.

Answer.

x

Common mistake.

Choosing y because it was written last: later code does not override an earlier rule.

Worked example: Two functions, one address

Problem.

What does GET /a return?

Idea.

Rules are tried in the order they were registered.

  1. x is registered first for /a.
  2. y is registered second for the same path.
  3. The first rule answers.

Answer.

x

Common mistake.

Assuming the later function replaces the earlier one.

Tips and tricks
  • Compare the rule and the URL character by character, including the last slash.
  • A 404 means no rule matched; a 405 means a rule matched but the method is not allowed.
  • The function name does not decide the address. Only the rule string does.
Memory line

Slash in the rule: forgiving. Slash only in the request: 404.

Method for any exam question

StepDo this
1Look at the rule's last character.
2Compare it with the requested path.
3Rule has the slash, request does not: 308.
4Request has it, rule does not: 404.

5. Dynamic parts of a URL: placeholders and converters

A placeholder grabs one piece of the path; a converter decides what that piece may look like.

rules such as /user/<name> and /n/<int:n> that match many URLs

The question this lesson answers. Which pieces of an address does a placeholder accept, and what type reaches your function?

A slot with a shape

A placeholder is a slot in the address, and a converter gives the slot a shape. Digits fit the int slot; a piece containing / fits only the path slot.

A rule may contain a placeholder in angle brackets: @app.route("/user/<name>"). It matches /user/ followed by one non-empty segment (text with no /). The segment is passed to the view as a keyword argument with the same name.

@app.route("/user/<name>")
def user(name):
    return f"Hello, {name}!"
Converter

A converter is written <type:name>. It filters the segment and converts it: string (default) is any text without /; int is digits only; float is digits with a dot; path is like string but also accepts /.

Converters (Werkzeug 3.1)

RuleMatchesDoes not match (404)Value passed
/u/<name>/u/Ana, /u/07/u/, /u/a/bstr
/n/<int:n>/n/5, /n/007/n/-1, /n/5.0, /n/abcint
/f/<float:x>/f/5.5/f/55, /f/abcfloat
/p/<path:x>/p/a/b/c/p/str with slashes

Worked example: An empty segment

Problem.

With the user rule above, what do /user/Ana, /user/07 and /user/ give?

Idea.

A placeholder needs one non-empty segment; the default converter gives text.

  1. /user/Ana: segment Ana → Hello, Ana! (200).
  2. /user/07: segment 07 is text, so Hello, 07! (200); nothing turns it into the number 7.
  3. /user/: the segment after /user/ is empty, so the rule does not match: 404.

Answer.

Hello, Ana!, Hello, 07!, Not Found

Common mistake.

Expecting /user/ to call user with an empty name.

Worked example: path versus the default converter

Problem.

Rule A is @app.route("/files/<path:p>") returning p; rule B, in a different app, is @app.route("/docs/<p>") returning p. What do /files/a/b.txt and /docs/a/b.txt give?

Idea.

Only path lets a placeholder span slashes.

  1. /files/a/b.txt: the path converter takes a/b.txt, slashes included: output a/b.txt (200).
  2. /docs/a/b.txt: the default converter stops at a slash, so <p> could only be a, leaving /b.txt unmatched.
  3. No rule matches the whole path: 404.

Answer.

a/b.txt (200) and Not Found (404)

Common mistake.

Thinking the default converter takes the rest of the URL.

Trap

A converter mismatch is never a Python error. /n/abc with <int:n> does not reach the view at all: it is a plain 404.

What each converter really accepts. A converter is a small filter on one segment of the path. If the segment does not fit the filter, the rule simply does not match, and with no other rule the answer is 404. The table below lists the edge cases the exam likes.

Converter edge cases

RuleRequestResult
/f/<float:x>/f/3404: float needs a decimal point
/f/<float:x>/f/3.5200, x = 3.5
/n/<int:x>/n/007200, x = 7 (leading zeros are fine)
/p/<path:p>/p/a/b/c200, p = "a/b/c" (path allows slashes)
/s/<s>/s/a/b404: the default converter stops at a slash
/s/<s>/s/a%20b200, s = "a b" (the %20 is decoded)

Worked example: Float or not?

Problem.

Rule /price/<float:p>. Requests: /price/10, /price/10.0, /price/-2.5.

Idea.

float wants digits with a decimal point; like int, it rejects a minus sign by default.

  1. /price/10 has no decimal point → no match, 404.
  2. /price/10.0 → match, p = 10.0.
  3. /price/-2.5 starts with a minus → no match, 404.

Answer.

Only /price/10.0

Common mistake.

Expecting /price/10 to match because 10 is a number: the converter checks the text, not the value.

Worked example: Two rules compete

Problem.

What do /item/5 and /item/abc return?

Idea.

The more specific converter is preferred, whatever the order.

  1. /item/5 fits both rules.
  2. The int rule is more specific, so it wins although it is written second.
  3. abc fits only the name rule.

Answer.

number 5 and name abc

Common mistake.

Applying the first-registered rule here. That applies to identical rules.

Tips and tricks
  • Test each segment against its converter before reading the function body.
  • With no converter the value arrives as a string, so + joins text.
  • Only path can swallow a slash.

Turning a list into the response text. Views often build a list of numbers and return it as one string. map(str, a) turns every number into text, and ", ".join(...) glues the pieces with a comma and a space between them. The separator appears only between items, never at the end.

Numbers up to n as one string

n = 3
a = [i for i in range(n + 1)]
print(a)                      # [0, 1, 2, 3]
print(", ".join(map(str, a)))  # 0, 1, 2, 3
Two details to check

range(n + 1) starts at 0 and includes n. join accepts only strings: ", ".join([1, 2]) raises TypeError, which is why map(str, ...) is there.

Memory line

A converter that rejects gives 404, never a Python error.

Method for any exam question

StepDo this
1Split the address at each slash.
2Test each piece against its converter.
3Convert the value to that type.
4If any piece fails, answer 404.

6. Building URLs with url_for

url_for works backwards: from a function name to its address.

how url_for turns a function name and some values into a URL

The question this lesson answers. Given a call to url_for, what exact text comes out? Work backwards: from a function name to its address.

Picture it

Saving a contact by name: when the number changes, calls made by name still reach the person.

Hard-coding addresses such as "/user/Ana" breaks when a route changes. url_for builds the address from the route table instead. Its first argument is the endpoint: the name of the view function (not the URL).

url_for

url_for(endpoint, **values) returns the URL of the route whose function is endpoint. Values whose names match placeholders fill them in; every other value is added to the query string.

from flask import Flask, url_for

app = Flask(__name__)

@app.route("/user/<username>")
def profile(username):
    return f"{username}'s page"

with app.test_request_context():
    print(url_for("profile", username="Ana"))
    print(url_for("profile", username="Ana", tab="posts"))

Reading a url_for call

CallResultWhy
url_for("profile", username="Ana")/user/Anafills <username>
url_for("profile", username="Ana", tab="posts")/user/Ana?tab=postsextra value → query string
url_for("/user/Ana")error (BuildError)a URL is not an endpoint name
url_for("profile")error (BuildError)the placeholder has no value

Worked example: Placeholders and extras

Problem.

Route @app.route("/item/<int:id>") on def item(id). Inside test_request_context(), what does print(url_for("item", id=7, page=2)) print?

Idea.

Fill placeholders first; leftovers become ?key=value.

  1. The endpoint is item, whose rule is /item/<int:id>.
  2. id=7 fills the placeholder: /item/7.
  3. page=2 has no placeholder, so it is appended as ?page=2.

Answer.

/item/7?page=2

Common mistake.

Writing /item/7/2: extra values never become path segments.

Worked example: Endpoint name versus path

Problem.

@app.route("/home") sits above def index(): .... What do url_for("index") and url_for("home") give?

Idea.

The endpoint is the function name, so home names nothing.

  1. The rule /home is registered under the endpoint index.
  2. url_for("index") returns /home.
  3. No function is called home, so url_for("home") raises BuildError.

Answer.

/home, and an error (BuildError)

Common mistake.

Passing the path word (home) instead of the function name (index).

Trap

url_for returns text. It does not run the view, so print(url_for("index")) prints /home, never the page content.

Exam tip

For "what does url_for(...) print" questions: (1) find the function by name, (2) copy its rule, (3) fill placeholders, (4) put every other value after ?.

url_for in four situations. It builds the path from the rule, escapes anything unsafe, adds a full address only when asked, and turns every value the rule does not use into the query string.

What url_for returns

CallResultRule it shows
url_for("user", name="a b")/user/a%20bunsafe characters are escaped
url_for("user", name="x", _external=True)http://localhost/user/x_external adds scheme and host
url_for("static", filename="x.css")/static/x.cssthe built-in static endpoint
url_for("user", name="q", tab=1)/user/q?tab=1extra values go to the query string

Worked example: Build three links

Problem.

Rule @app.route("/user/<name>") on def user(name).

Idea.

The rule fills name; anything else becomes ?key=value.

  1. "Ann Lee" has a space, which is escaped as %20: /user/Ann%20Lee.
  2. page is not in the rule: /user/ann?page=2.

Answer.

/user/Ann%20Lee and /user/ann?page=2

Common mistake.

Writing /user/Ann Lee with a raw space, or putting page into the path.

Worked example: Lists, None and zero

Problem.

For the index view at /home, what do url_for("index", tag=["a", "b"]), url_for("index", q=None) and url_for("index", page=0) give?

Idea.

Extra values become the query string.

  1. A list repeats its key once for each item.
  2. A value of None is left out.
  3. Zero is a real value and is kept.

Answer.

/home?tag=a&tag=b, /home, /home?page=0

Common mistake.

Dropping page=0 because zero counts as false.

Memory line

Function name in, address out. Leftovers go after ?.

Method for any exam question

StepDo this
1Find the function named in the first argument.
2Copy its rule.
3Fill the placeholders by name.
4Put every other value in the query string.

7. Redirects

A redirect says "go there instead"; the browser makes a second request.

redirect(...): a response that tells the browser to request another URL

The question this lesson answers. When a view calls redirect, whose text does the user finally see? Follow the messages one at a time.

redirect(location) does not build a page. It returns a short response with status 302 Found and a Location header. The browser reads the header, sends a new GET request to that address, and shows whatever that second request returns.

Picture it

A receptionist who says "that office moved to room 302". You walk to room 302 and talk to whoever is there. What you finally hear depends only on room 302.

from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route("/old")
def old():
    return redirect(url_for("new"))

@app.route("/new")
def new():
    return "New page"

Worked example: Following one redirect

Problem.

With the app above, the browser opens /old. List both responses and say what is shown.

Idea.

A redirect is a pointer; read the page at its target.

  1. GET /old runs old(), which returns redirect("/new"): status 302, Location: /new.
  2. The browser sends GET /new, which runs new(): status 200, body New page.
  3. The address bar now shows /new and the page shows New page.

Answer.

302 then 200; the browser shows New page

Common mistake.

Answering with something from old(); it returns no page at all.

Worked example: A redirect that depends on the path

Problem.

Trace GET /enter/meera?floor=2 through the app below.

Idea.

No view here reads the query string; only the path decides.

  1. /enter/meera matches /enter/<who> with who = "meera"; ?floor=2 is not used.
  2. who is not "staff", so it returns a redirect to url_for("queue", who="meera"), which is /queue/meera.
  3. The browser requests /queue/meera: the reply is Queue for meera.

Answer.

Queue for meera

Common mistake.

Letting ?floor=2 change the answer; nothing reads request.args.

Notice

Two different redirects appear in Flask questions: 302 from your own redirect(...) call, and 308 that Werkzeug adds for a missing trailing slash. Either way the browser follows it, so "what does the browser render" means the page at the end.

What actually travels. A redirect is a short response with a status code and a Location header; the browser then makes a brand-new GET to that location. redirect(...) uses 302 unless you pass code=. In Flask 3 the Location header holds the path as given, such as /b.

Worked example: 301 or 302?

Problem.

return redirect("/b", code=301) in route /c.

Idea.

The code argument sets the status; the browser follows either one.

  1. code=301 → status 301, Location /b.
  2. The browser requests /b and shows B.

Answer.

301, then B

Common mistake.

Thinking 301 shows a different page from 302: both send the browser to the same place; 301 also says the move is permanent.

Worked example: A redirect into a missing slash

Problem.

The browser asks for /go. List every status code it receives and the final text.

Idea.

Each redirect starts a new request, which is matched from scratch.

  1. /go answers 302 with location /docs.
  2. The rule is /docs/, so the request for /docs is answered 308.
  3. The request for /docs/ runs docs and answers 200.

Answer.

302, 308, 200; the page shows Docs.

Common mistake.

Counting only the redirect written in the code.

Tips and tricks
  • Follow the redirect and answer with what the second route returns.
  • url_for takes the function name, not the URL text.
  • The address bar ends up showing the new URL.
Memory line

A redirect is a note saying where to ask next.

Method for any exam question

StepDo this
1Run the first view and note the status and location.
2Make a new GET to that location.
3Repeat until a non-redirect status.
4The last view's text is what shows.

8. Reading what the browser sent

Data arrives in the path, the query string, or the body; each has its own reader.

request.args, request.form, request.get_json() and the methods list

The question this lesson answers. A value arrives with a request. Where is it, what type is it, and what happens if it is not there?

Three pockets

A request has three pockets: the path, the query string and the body. Each has its own reader, and looking in the wrong pocket finds nothing.

A request can carry data in three places. The path is matched against routes (placeholders). The query string after ? is read with request.args. The body of a POST is read with request.form (HTML forms) or request.get_json() (JSON). request must be imported from flask.

Where data comes from

Data inExampleRead withMissing value
path/user/7 with /user/<id>view parameter idrule does not match: 404
query string/search?q=flaskrequest.args.get("q")None (or your default)
form body (POST)<input name="q">request.form.get("q")None
JSON body (POST){"q": "flask"}request.get_json()["q"]Python KeyError → 500
from flask import Flask, request

app = Flask(__name__)

@app.route("/search")
def search():
    q = request.args.get("q")
    page = request.args.get("page", "1")
    return q + " " + page
Two ways to read, two outcomes

request.args["k"] with no k in the URL stops the request with 400 Bad Request. request.args.get("k") returns None and the view carries on. ?k or ?k= gives the empty string "".

Methods

A route accepts only the methods listed in methods=[...]; the default is ["GET"]. A browser address bar always sends GET. Flask checks the method before the view runs: a disallowed method gets 405 Method Not Allowed.

Worked example: Query values with defaults

Problem.

With search above, what do /search?q=flask&page=2, /search?q=flask and /search?page=2 give?

Idea.

.get returns the value, the default, or None.

  1. First URL: q = "flask", page = "2": returns flask 2.
  2. Second URL: no page, so the default "1": returns flask 1.
  3. Third URL: no q, so q = None. None + " " raises TypeError in the view, and the response is 500 Internal Server Error.

Answer.

flask 2, flask 1, Internal Server Error (500)

Common mistake.

Expecting a 400 for the third URL; .get never raises, the later + does.

Worked example: A POST-only JSON route and curl

Problem.

Predict the status for each command against the route below.

Idea.

Check the method first; only then read the body.

  1. (1) --json sends the body with POST. POST is allowed, so the view runs: the course is mad1, so it books 2 seats.
  2. (2) -X PUT changes the method. PUT is not in methods, so Flask answers 405 before the view runs.
  3. (3) POST is allowed and the view runs, but the course does not match, so the last line answers.

Answer.

(1) 200 Booked 2, (2) 405, (3) 200 No such course

Common mistake.

Giving the view's text for the PUT request; the view never runs.

Repeated keys and typed reads. A query string may repeat a key, as in ?t=a&t=b. request.args.get("t") gives only the first value; request.args.getlist("t") gives all of them. get also accepts type=int: if the text is not a number you get the default (None unless you give one) instead of an error.

Reading /t?t=a&t=b&n=x

ExpressionValue
request.args.get("t")"a"
request.args.getlist("t")["a", "b"]
request.args.get("n", type=int)None ("x" is not an int)
request.args.get("n", 5, type=int)5

Worked example: A safe page number

Problem.

page = request.args.get("page", 1, type=int). Requests: /list, /list?page=3, /list?page=abc.

Idea.

Missing or not a number → the default.

  1. /list: no page → 1.
  2. /list?page=3 → 3 (converted to int).
  3. /list?page=abc: conversion fails → 1.

Answer.

1, 3, 1

Common mistake.

Expecting a 400 error for abc: type= swallows the failure and uses the default.

Worked example: Adding query values

Problem.

What does /add?a=2&b=3 return?

Idea.

Query values are text.

  1. a is "2" and b is "3".
  2. Plus joins two strings.
  3. No number is ever created.

Answer.

23

Common mistake.

Answering 5.

Will two returned pages look different? The browser draws the HTML you return. A <p> is a block element: it takes its own line and leaves a margin above and below. A <span> is an inline element: it adds no line break and no margin of its own, so it sits in the flow of the text around it. A block element still ends its own line, so whatever comes after it starts lower down.

Returned HTMLWhat you see
<p>IIT</p><p>MADRAS</p>IIT, then MADRAS on a new line
<p>IIT</p><span>MADRAS</span>IIT, then MADRAS on a new line: the <p> above ended the line
<span>IIT</span><span>MADRAS</span>IITMADRAS on one line
Different tags can look the same

The first two rows have different source code but look alike. When a question asks whether the output looks similar, picture the screen, not the tags. Styles set on <body> (colour, centring, bold) apply to both kinds.

Memory line

Every value is text until you convert it.

Method for any exam question

StepDo this
1Decide which pocket holds the value.
2Check whether get or square brackets is used.
3Apply the default only if the key is missing.
4Convert the type before doing arithmetic.

9. abort and error handlers

abort stops with an error code; an error handler decides what that error looks like.

stopping a view with abort(code) and replacing error pages with @app.errorhandler(code)

The question this lesson answers. Something goes wrong. Which page appears, and with which status code? The two are decided separately.

One app for the whole lesson

from flask import Flask, abort
app = Flask(__name__)

@app.route("/seat/<code>")
def seat(code):
    if not code.isalnum():
        abort(400, "letters and digits only")
    number = int(code[1:])
    return f"Row {code[0]}, seat {number}"

Before stepping: for each request, say whether it fails at the path, the method, the guard, in the code, or nowhere.

abort(code, description) raises an exception immediately: no line after it runs. Flask catches it and sends an error page with that status code. The description becomes the message on the page.

String tests used in abort questions

MethodTrue when"MAD-I""CS2003""101"
isalpha()all lettersFalseFalseFalse
isalnum()all letters or digitsFalseTrueTrue
isnumeric() / isdigit()all digitsFalseFalseTrue
Error handler

@app.errorhandler(404) above a function makes it the page for every 404, whether it came from an unknown URL or from abort(404). Its return value becomes the response. A plain string is sent with status 200: to keep 404 you must return (body, 404).

Add a 404 handler to the seat app: GET /seat

The handler returnsBodyStatus
"No such page"No such page200
("No such page", 404)No such page404

Worked example: A handler's status code

Problem.

An app has @app.errorhandler(404) returning "custom". A browser requests a URL that matches no route. What is the body and the status? What changes if the handler returns ("custom", 404)?

Idea.

The handler's return value is used exactly like a view's.

  1. No rule matches, so Flask raises 404 and looks for a 404 handler.
  2. The handler returns the string custom: body custom, and a plain string means status 200.
  3. With return "custom", 404 the tuple sets the status: body custom, status 404.

Answer.

custom with 200; then custom with 404

Common mistake.

Assuming the handler keeps the 404 automatically.

Worked example: The method check comes first

Problem.

A browser opens /report/week3.

Idea.

Routing and the method check happen before the view, so abort(403) is never reached.

  1. The path matches the rule.
  2. A browser sends GET, but only PUT is allowed, so Flask raises 405 without calling report.
  3. The 405 handler runs.

Answer.

Use the right method

Common mistake.

Following the view's abort(403): the view never runs.

Worked example: A handler that keeps the code

Problem.

What are the replies to /item/2, /item/9 and /other?

Idea.

The handler serves every 404 and here returns the status itself.

  1. /item/2 runs normally.
  2. /item/9 calls abort(404), which the handler answers.
  3. /other matches no rule, which is also a 404.

Answer.

200 2; 404 gone; 404 gone

Common mistake.

Treating the abort and the unknown address differently.

Memory line

The handler chooses the page; its return chooses the status.

10. Forms, frontend and backend validation

The browser checks the HTML rules; your Python checks the rest.

a view that shows a form on GET and checks it on POST

The question this lesson answers. If the browser already checks a form, why check again in Python? Because a request can arrive without any browser.

Picture it

A guard at the gate helps honest visitors, but the lock on the vault is what protects it. Browser checks are the guard; server checks are the lock.

A typical form route accepts both GET and POST. On GET it returns the HTML form. When the user submits, the browser sends POST with the form fields in the body, and the same view reads them with request.form.

@app.route("/signup", methods=["GET", "POST"])
def signup():
    if request.method == "GET":
        return """<form method="post">
          <input name="user" required>
          <input name="pwd" type="password" minlength="8">
          <button>Join</button></form>"""
    pwd = request.form.get("pwd", "")
    if len(pwd) < 8:
        return redirect(url_for("signup"))
    return "Welcome, " + request.form.get("user") + "!"

Frontend versus backend validation

Frontend (HTML5)Backend (in the view)
Written asrequired, minlength, maxlength, type="email"if checks on request.form values
Runs inthe browser, before sendingFlask, after the request arrives
Can be skippedyes (curl, edited HTML)no
Messagethe browser's own, e.g. "Please fill out this field."whatever your view returns
Dynamic and server-side rendered

A page is dynamically generated when Python builds its HTML for each request (a returned string or a template), and server-side rendered (SSR) when that HTML is built on the server and sent complete. A static page is a fixed file sent as it is.

Worked example: The backend check catches what HTML missed

Problem.

Someone posts to /signup with curl, skipping the browser: user=ana, pwd=abc. Then again with pwd=abcdefgh. What happens?

Idea.

curl ignores HTML attributes, so only the Python check stands.

  1. curl sends POST directly, so required and minlength never run.
  2. First request: len("abc") = 3 < 8, so the view returns a redirect (302) to /signup.
  3. Second request: the length is 8, so it returns Welcome, ana! (200).

Answer.

A redirect back to the form, then Welcome, ana!

Common mistake.

Believing HTML5 attributes protect the server.

Worked example: Classify the validation

Problem.

Classify the signup view: is the form static or dynamic? Which validation types does it use?

Idea.

Look for HTML attributes (frontend) and Python if checks (backend).

  1. The form HTML is returned by a Python function for each GET, so it is dynamically generated and server-side rendered.
  2. required and minlength are HTML5 attributes: frontend validation.
  3. if len(pwd) < 8 in the view: backend validation.

Answer.

Dynamic (SSR); both frontend and backend validation

Common mistake.

Calling it static because the HTML text never changes; what matters is that Python sends it per request.

Reading a field that is not there. request.form["x"] with no field x in the posted form stops the request with 400 Bad Request. request.form.get("x", "none") returns the default instead. The same rule holds for request.args.

Two ways to read a form field

request.form["x"]request.form.get("x", d)
Field sentits valueits value
Field missing400 Bad Requestd (None if no default)
Use whenthe field is requiredthe field is optional

Worked example: Missing field

Problem.

@app.route("/f", methods=["POST"]) returns request.form["x"]. A form posts only y=1.

Idea.

Square brackets require the key.

  1. x is missing from request.form.
  2. Flask raises BadRequestKeyError, which is a 400.

Answer.

400

Common mistake.

Answering 500: a missing form key is the client's mistake, so Flask answers 400.

Worked example: An unticked box

Problem.

A form has a checkbox named agree that the user leaves unticked. The view returns request.form.get("agree") inside an f-string. What is shown?

Idea.

An unticked checkbox sends nothing at all.

  1. No agree field arrives.
  2. get returns None.
  3. The f-string turns it into the word None.

Answer.

None

Common mistake.

Expecting an empty string or the word off.

Tips and tricks
  • request.form holds POST fields; request.args holds the values after ? in the URL.
  • request.form["x"] on a missing field gives a 400 error; .get("x") gives None.
  • Browser checks can be bypassed, so a server check is still needed.
Memory line

The browser check helps the user; the server check protects you.

Method for any exam question

StepDo this
1Split GET from POST.
2List the fields that really arrive.
3Square brackets need the field; get does not.
4Run your own checks in order.

Practise this topic →

Weeks covering this topic

Other MAD 1 topics