How a request becomes a response in Flask, needed by the templating, REST and database chapters.
Open the interactive lessons →Flask Web Framework past questions
Contents
- Start here: the Python and HTTP you need, from zero
- One request, one function, one response
- What a view may return
- Routes, stacked routes and the trailing slash
- Dynamic parts of a URL: placeholders and converters
- Building URLs with url_for
- Redirects
- Reading what the browser sent
- abort and error handlers
- 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
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
| Part | Example | Who reads it in Flask |
|---|---|---|
| method | GET, POST | the route's methods list |
| path | /user/7 | the route rules |
| query string | ?tab=info | request.args |
| body | form fields or JSON | request.form, request.json |
| status code (in the reply) | 200, 302, 404, 405, 500 | what the browser does next |
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.
- /hi/Asha matches with name = "Asha".
- The view returns "Hi Asha!".
- 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.
- The view runs and finishes without return.
- It gives back None.
- 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
| Step | Do this |
|---|---|
| 1 | Match the method and path to a route. |
| 2 | Take values from the path, the query string or the body. |
| 3 | Run the function line by line. |
| 4 | What 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.
- The key
nexists, with value 0. - So the first call gives 0.
- The key
mis missing. - 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.
<n>has no converter, sonis the string "7".- A string times 2 repeats it.
- The reply is 77.
Answer.
77
Common mistake.
Answering 14, which needs <int:n>.
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.
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 /).
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.
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 others | status code: 200, 302, 404 and others |
path: /user/7 | headers, such as Content-Type |
query string: ?tab=info | body: 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.
- The route table has one rule:
/→home. /matches, sohome()runs and returnsHello, MAD 1!: status 200./aboutmatches 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.
/hellomatches the rule exactly: the function runs.- It returns the HTML
<h1>Hello MAD</h1>, so the browser shows Hello MAD as a heading, status 200. /Hellohas 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.
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.
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
| Request | Status | Why |
|---|---|---|
| GET / | 200 | the default method of every route |
| HEAD / | 200 with an empty body | added by Flask for every GET route |
| OPTIONS / | 200 | added by Flask to report the allowed methods |
| POST / | 405 | the 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.
- GET /login: the path matches, but only POST is allowed → 405.
- POST /login: path and method match → the view runs, 200.
- 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.
- The path is
/a. - The query string is not part of the match.
Answer.
200.
Common mistake.
Answering 404 because the rule has no x.
No path: 404. Wrong method: 405. Both fine: your function.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Write the route table: path, function, methods. |
| 2 | Match the path exactly, including capital letters. |
| 3 | Check the method. |
| 4 | Only 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 returns | Body | Status | Content-Type |
|---|---|---|---|
"text" or an HTML string | the string | 200 | text/html |
{"a": 1} | {"a":1} | 200 | application/json |
[1, 2] | [1,2] | 200 | application/json |
("made", 201) | made | 201 | text/html |
redirect(...) | short redirect page | 302 | text/html |
None (or no return) | error page | 500 | text/html |
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.
- The first item is a dict, so Flask converts it to JSON:
{"user":"ana"}. - The second item, 201, becomes the status code.
- 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.
- First iteration:
uis ana."ana" == "bob"is False, so theelsebranch runs. return "Unauthorized"ends the function on the first user.- 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
| Return | Status | Notes |
|---|---|---|
"made", 201 | 201 | body plus status |
"h", {"X-A": "1"} | 200 | body plus headers |
"t", 202, {"X-B": "2"} | 202 | body, status, headers |
[1, 2] | 200 | sent as JSON |
5 | 500 | an 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.
- The dict becomes a JSON body.
- 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.
- The view returns the integer 5.
- Flask accepts text, dictionaries, lists, tuples and response objects.
- An integer raises a
TypeError, which becomes a 500.
Answer.
500
Common mistake.
Expecting a page showing 5. Return str(5) for that.
- 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.
Text is a page, a dictionary is JSON, nothing is a crash.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Read the return line that actually runs. |
| 2 | Name its type. |
| 3 | Look for a status in a tuple. |
| 4 | No 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"
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 code | URL requested | Result |
|---|---|---|
/about | /about | 200 |
/about | /about/ | 404 Not Found |
/docs/ | /docs/ | 200 |
/docs/ | /docs | 308 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.
- Route table:
/start→start,/begin→start. /startmatches rule 1:Let us begin, 200./beginmatches rule 2: the same function runs:Let us begin, 200./stopmatches 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.
/menu/matches exactly:Menu, 200./menuis the same rule without its slash: Flask replies 308 withLocation: /menu/.- The browser follows the redirect, requests
/menu/and showsMenu. /menu/xhas 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.
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 functions | Same 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 shows | at request time: /a runs x | at start-up: the app refuses to load |
| Result | the first registered wins | AssertionError: "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.
- Both rules match /a.
xwas registered first.- 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.
xis registered first for/a.yis registered second for the same path.- The first rule answers.
Answer.
x
Common mistake.
Assuming the later function replaces the earlier one.
- 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.
Slash in the rule: forgiving. Slash only in the request: 404.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Look at the rule's last character. |
| 2 | Compare it with the requested path. |
| 3 | Rule has the slash, request does not: 308. |
| 4 | Request 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 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}!"
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)
| Rule | Matches | Does not match (404) | Value passed |
|---|---|---|---|
/u/<name> | /u/Ana, /u/07 | /u/, /u/a/b | str |
/n/<int:n> | /n/5, /n/007 | /n/-1, /n/5.0, /n/abc | int |
/f/<float:x> | /f/5.5 | /f/55, /f/abc | float |
/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.
/user/Ana: segmentAna→Hello, Ana!(200)./user/07: segment07is text, soHello, 07!(200); nothing turns it into the number 7./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.
/files/a/b.txt: thepathconverter takesa/b.txt, slashes included: outputa/b.txt(200)./docs/a/b.txt: the default converter stops at a slash, so<p>could only bea, leaving/b.txtunmatched.- 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.
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
| Rule | Request | Result |
|---|---|---|
/f/<float:x> | /f/3 | 404: float needs a decimal point |
/f/<float:x> | /f/3.5 | 200, x = 3.5 |
/n/<int:x> | /n/007 | 200, x = 7 (leading zeros are fine) |
/p/<path:p> | /p/a/b/c | 200, p = "a/b/c" (path allows slashes) |
/s/<s> | /s/a/b | 404: the default converter stops at a slash |
/s/<s> | /s/a%20b | 200, 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.
- /price/10 has no decimal point → no match, 404.
- /price/10.0 → match, p = 10.0.
- /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.
/item/5fits both rules.- The
intrule is more specific, so it wins although it is written second. abcfits only the name rule.
Answer.
number 5 and name abc
Common mistake.
Applying the first-registered rule here. That applies to identical rules.
- Test each segment against its converter before reading the function body.
- With no converter the value arrives as a string, so
+joins text. - Only
pathcan 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
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.
A converter that rejects gives 404, never a Python error.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Split the address at each slash. |
| 2 | Test each piece against its converter. |
| 3 | Convert the value to that type. |
| 4 | If 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.
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(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
| Call | Result | Why |
|---|---|---|
url_for("profile", username="Ana") | /user/Ana | fills <username> |
url_for("profile", username="Ana", tab="posts") | /user/Ana?tab=posts | extra 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.
- The endpoint is
item, whose rule is/item/<int:id>. id=7fills the placeholder:/item/7.page=2has 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.
- The rule
/homeis registered under the endpointindex. url_for("index")returns/home.- No function is called
home, sourl_for("home")raisesBuildError.
Answer.
/home, and an error (BuildError)
Common mistake.
Passing the path word (home) instead of the function name (index).
url_for returns text. It does not run the view, so print(url_for("index")) prints /home, never the page content.
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
| Call | Result | Rule it shows |
|---|---|---|
url_for("user", name="a b") | /user/a%20b | unsafe 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.css | the built-in static endpoint |
url_for("user", name="q", tab=1) | /user/q?tab=1 | extra 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.
- "Ann Lee" has a space, which is escaped as %20: /user/Ann%20Lee.
- 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.
- A list repeats its key once for each item.
- A value of
Noneis left out. - 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.
Function name in, address out. Leftovers go after ?.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Find the function named in the first argument. |
| 2 | Copy its rule. |
| 3 | Fill the placeholders by name. |
| 4 | Put 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.
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.
GET /oldrunsold(), which returnsredirect("/new"): status 302,Location: /new.- The browser sends
GET /new, which runsnew(): status 200, bodyNew page. - The address bar now shows
/newand the page showsNew 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.
/enter/meeramatches/enter/<who>withwho = "meera";?floor=2is not used.whois not"staff", so it returns a redirect tourl_for("queue", who="meera"), which is/queue/meera.- The browser requests
/queue/meera: the reply isQueue for meera.
Answer.
Queue for meera
Common mistake.
Letting ?floor=2 change the answer; nothing reads request.args.
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.
- code=301 → status 301, Location /b.
- 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.
/goanswers 302 with location/docs.- The rule is
/docs/, so the request for/docsis answered 308. - The request for
/docs/runsdocsand answers 200.
Answer.
302, 308, 200; the page shows Docs.
Common mistake.
Counting only the redirect written in the code.
- Follow the redirect and answer with what the second route returns.
url_fortakes the function name, not the URL text.- The address bar ends up showing the new URL.
A redirect is a note saying where to ask next.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Run the first view and note the status and location. |
| 2 | Make a new GET to that location. |
| 3 | Repeat until a non-redirect status. |
| 4 | The 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?
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 in | Example | Read with | Missing value |
|---|---|---|---|
| path | /user/7 with /user/<id> | view parameter id | rule does not match: 404 |
| query string | /search?q=flask | request.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
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 "".
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.
- First URL:
q = "flask",page = "2": returnsflask 2. - Second URL: no
page, so the default"1": returnsflask 1. - Third URL: no
q, soq = None.None + " "raisesTypeErrorin 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)
--jsonsends the body with POST. POST is allowed, so the view runs: the course ismad1, so it books2seats. - (2)
-X PUTchanges the method. PUT is not inmethods, so Flask answers 405 before the view runs. - (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
| Expression | Value |
|---|---|
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.
- /list: no page → 1.
- /list?page=3 → 3 (converted to int).
- /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.
ais "2" andbis "3".- Plus joins two strings.
- 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 HTML | What 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 |
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.
Every value is text until you convert it.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Decide which pocket holds the value. |
| 2 | Check whether get or square brackets is used. |
| 3 | Apply the default only if the key is missing. |
| 4 | Convert 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
| Method | True when | "MAD-I" | "CS2003" | "101" |
|---|---|---|---|---|
isalpha() | all letters | False | False | False |
isalnum() | all letters or digits | False | True | True |
isnumeric() / isdigit() | all digits | False | False | True |
@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 returns | Body | Status |
|---|---|---|
"No such page" | No such page | 200 |
("No such page", 404) | No such page | 404 |
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.
- No rule matches, so Flask raises 404 and looks for a 404 handler.
- The handler returns the string
custom: bodycustom, and a plain string means status 200. - With
return "custom", 404the tuple sets the status: bodycustom, 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.
- The path matches the rule.
- A browser sends GET, but only PUT is allowed, so Flask raises 405 without calling
report. - 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.
/item/2runs normally./item/9callsabort(404), which the handler answers./othermatches no rule, which is also a 404.
Answer.
200 2; 404 gone; 404 gone
Common mistake.
Treating the abort and the unknown address differently.
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.
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 as | required, minlength, maxlength, type="email" | if checks on request.form values |
| Runs in | the browser, before sending | Flask, after the request arrives |
| Can be skipped | yes (curl, edited HTML) | no |
| Message | the browser's own, e.g. "Please fill out this field." | whatever your view returns |
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.
- curl sends POST directly, so
requiredandminlengthnever run. - First request:
len("abc") = 3 < 8, so the view returns a redirect (302) to/signup. - 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).
- The form HTML is returned by a Python function for each GET, so it is dynamically generated and server-side rendered.
requiredandminlengthare HTML5 attributes: frontend validation.if len(pwd) < 8in 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 sent | its value | its value |
| Field missing | 400 Bad Request | d (None if no default) |
| Use when | the field is required | the 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.
- x is missing from request.form.
- 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.
- No
agreefield arrives. getreturnsNone.- The f-string turns it into the word None.
Answer.
None
Common mistake.
Expecting an empty string or the word off.
request.formholds POST fields;request.argsholds the values after?in the URL.request.form["x"]on a missing field gives a 400 error;.get("x")givesNone.- Browser checks can be bypassed, so a server check is still needed.
The browser check helps the user; the server check protects you.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Split GET from POST. |
| 2 | List the fields that really arrive. |
| 3 | Square brackets need the field; get does not. |
| 4 | Run your own checks in order. |