The Analogy: A Ship-and-Print Store's Drop-Off Counter
Picture the counter of a busy pack-and-ship store on a Monday morning. Customers stream in to send parcels, and the information the clerk needs arrives through several completely different channels at once. Some details are printed on a slip the customer prepared on the store's website the night before and now carries in their hand -- an order reference, a pickup-location code. Other details the customer writes out by hand on a paper consignment form at the counter: the recipient's name, the delivery address, the service level. And then there are the parcels themselves, lifted onto the counter, weighed, and set aside for labelling. Three channels, three kinds of thing, and the clerk has to know which is which.
The pre-printed slip is like a reference tag: short, visible, carried openly, and used mainly to look something up or to say "this is the counter I meant." The clerk never treats the slip as the whole order -- it just points at one. The handwritten consignment form is the real submission: it is where the customer states what they actually want done, and it can be long, private, and detailed. The parcels are a third thing entirely; you do not read a parcel the way you read a form, you weigh it, inspect it, and give it a proper label before it enters the network. A clerk who confused these -- who tried to weigh the slip or mail the form -- would grind the queue to a halt.
Some customers make the channels busier still. A small business owner sends five parcels in one visit, writing each recipient on its own line of the same form, so a single field -- "recipient" -- now carries five answers, not one. A clerk who reads only the first line and waves the rest through has just lost four shipments. The competent clerk knows that one labelled box on the form can legitimately hold a whole list, and reads every line. In the same way, one visitor may hand over both a pre-printed slip and a handwritten form that mention the same field, and the clerk must have a settled rule for which one wins when they disagree.
The failure that ruins the day is the clerk who treats everything the customer provides as already true. A parcel arrives with a hand-written label reading "contents: books, value five dollars, fragile," a scrawled address, and a filename-like tag the customer wrote themselves; the clerk copies all of it onto the official shipping label without weighing the box, without checking the address against the account on the reference slip, and without questioning whether the declared contents are even allowed in the post. Everything the customer wrote was a claim, not a verified fact, and a counter that acts on unverified claims will cheerfully ship a mislabelled, mis-addressed, or outright prohibited parcel deep into the network before anyone notices. The channel tells you where a piece of information came from; it never tells you the information is safe to trust.
Syntax or Core Structure
Flask hands you the parsed request on the global request object, and it keeps the channels separate. request.args is the query string -- everything after the ? in the URL. request.form is the parsed body of a POST submitted as an HTML form. Both are dictionary-like, and both give you .get(key, default) so a missing field yields a fallback instead of raising a KeyError.
from flask import Flask, request
app = Flask(__name__)
@app.get("/search")
def search():
term = request.args.get("q", "")
page = request.args.get("page", "1")
return f"q={term} page={page}"
@app.post("/contact")
def contact():
name = request.form.get("name", "")
msg = request.form.get("message", "")
return f"from {name}: {msg}"
client = app.test_client()
print(client.get("/search?q=flask&page=2").get_data(as_text=True))
print(client.get("/search").get_data(as_text=True))
print(client.post("/contact", data={"name": "Ada", "message": "hi"}).get_data(as_text=True))
Output:
q=flask page=2
q= page=1
from Ada: hi
The first request supplies both query parameters, so they come through verbatim. The second supplies neither, and .get returns the defaults -- an empty term and page "1" -- rather than crashing. The POST reads its two fields from request.form, which is where the test client's data= dict lands. Notice every value is a string: page is "2", not the integer 2. Query and form data are always text, and turning "2" into a number (and rejecting "abc") is your job, not Flask's.
Technical Depth: Where Data Lives, Repeated Fields, and Uploads
The single word request hides several distinct containers, and reaching into the right one is most of the skill. Each attribute corresponds to one channel the data could have arrived through, and using the wrong one is why a value that is "obviously there" reads as empty.
| Attribute | Source | Type | Typical use |
|---|---|---|---|
| request.args | Query string after the ? | MultiDict | Filters, page numbers, flags |
| request.form | POST or PUT form body | MultiDict | Submitted form fields |
| request.values | args and form combined | CombinedMultiDict | Rarely; args win on a clash |
| request.files | Multipart file parts | MultiDict | Uploaded files |
| request.json | Parsed JSON body | dict or list | Clients sending JSON |
| request.data | Raw body bytes | bytes | Custom or unparsed payloads |
Query strings versus form bodies
The distinction matters because the same key can appear in both places. request.values merges the two into one view, which is convenient until they disagree -- and then you need to know the rule. Werkzeug builds request.values as the query args followed by the form, so on a collision the query string wins.
from flask import Flask, request
app = Flask(__name__)
@app.post("/merge")
def merge():
# request.values combines args (query) and form (body)
src = request.values.get("src", "?")
only_q = request.args.get("only_q", "?")
only_f = request.form.get("only_f", "?")
return f"src={src} only_q={only_q} only_f={only_f}"
client = app.test_client()
# 'src' appears in BOTH the query string and the form body
r = client.post("/merge?src=query&only_q=Q", data={"src": "form", "only_f": "F"})
print(r.get_data(as_text=True))
Output:
src=query only_q=Q only_f=F
The src key was sent twice -- ?src=query in the URL and src=form in the body -- and request.values returned query, the URL copy. This is a real source of bugs and of security surprises: an attacker who cannot control your form can sometimes still control the query string, so code that reads a security-relevant field from request.values may be reading a value the caller injected into the URL. Prefer reading from the specific container you mean -- request.form for a submitted form, request.args for a link -- and reach for request.values only when you genuinely want either.
Repeated fields and MultiDict
Both args and form are MultiDicts, not plain dicts, because HTML lets one field name appear many times -- a group of checkboxes named tag, a multi-select, a repeated query parameter. A plain .get collapses that to the first value, silently discarding the rest. When a field can repeat, use .getlist, which returns every value as a list.
from flask import Flask, request
app = Flask(__name__)
@app.get("/filter")
def filter_items():
tags = request.args.getlist("tag")
one = request.args.get("tag", "")
return f"getlist={tags} get={one} count={len(tags)}"
client = app.test_client()
print(client.get("/filter?tag=red&tag=blue&tag=green").get_data(as_text=True))
print(client.get("/filter?tag=solo").get_data(as_text=True))
print(client.get("/filter").get_data(as_text=True))
Output:
getlist=['red', 'blue', 'green'] get=red count=3
getlist=['solo'] get=solo count=1
getlist=[] get= count=0
Three values arrive under one key and getlist returns all three, while get returns only red, the first. With a single value getlist gives a one-item list; with the key absent it gives an empty list, never None -- so you can loop over it without a guard. The rule of thumb: if the UI could ever submit a field more than once, read it with getlist, and treat get as shorthand for "I expect exactly one."
File uploads and secure_filename
Uploaded files do not live in form -- they arrive in request.files, another MultiDict, but of FileStorage objects rather than strings. Each one carries the client-supplied filename, a stream you can .read() or .save(path), and a content_type. The single most important habit is to never use filename as-is: pass it through werkzeug.utils.secure_filename, which strips directory separators and unsafe characters so a malicious name cannot escape your upload directory.
import io
from flask import Flask, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.post("/upload")
def upload():
f = request.files.get("doc")
if f is None:
return "no file"
safe = secure_filename(f.filename)
body = f.read()
return f"orig={f.filename} safe={safe} bytes={len(body)}"
client = app.test_client()
data = {"doc": (io.BytesIO(b"hello world"), "report final.txt")}
print(client.post("/upload", data=data, content_type="multipart/form-data").get_data(as_text=True))
Output:
orig=report final.txt safe=report_final.txt bytes=11
The client named the file report final.txt; secure_filename returned report_final.txt, turning the space into an underscore. On a hostile name such as ../../etc/passwd it would return etc_passwd, with the traversal stripped out entirely. Reading the stream yields the eleven bytes of hello world. Two further guards belong with every upload: cap the size with app.config["MAX_CONTENT_LENGTH"] so a huge file cannot exhaust memory or disk, and validate the type yourself rather than trusting the client's content_type, which is trivially forged.
Real World Example: An Avatar Upload That Writes Wherever It Is Told
A profile page lets users upload an avatar. The obvious first version reads the file from request.files and saves it under the name the browser sent -- after all, that is the name the user chose. The hardened version beside it does three extra things: it runs the name through secure_filename, it checks the extension against a small allowlist, and it rejects anything else. Running both against the same hostile upload shows exactly why the shortcut is dangerous.
import io
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
app = Flask(__name__)
ALLOWED = {"png", "jpg", "pdf"}
@app.post("/avatar-bad")
def avatar_bad():
f = request.files["file"]
# VULNERABLE: trusts the client-supplied filename verbatim
return jsonify(stored_as=f.filename)
@app.post("/avatar-safe")
def avatar_safe():
f = request.files["file"]
name = secure_filename(f.filename)
ext = name.rsplit(".", 1)[-1].lower() if "." in name else ""
if ext not in ALLOWED:
return jsonify(error="type not allowed", ext=ext, safe_name=name), 400
return jsonify(stored_as=name)
client = app.test_client()
def send(url, filename):
data = {"file": (io.BytesIO(b"x"), filename)}
return client.post(url, data=data, content_type="multipart/form-data")
print("bad :", send("/avatar-bad", "../../etc/cron.d/evil.sh").get_json()["stored_as"])
r = send("/avatar-safe", "../../etc/cron.d/evil.sh")
j = r.get_json()
print("safe:", r.status_code, j["error"], "ext=" + j["ext"], "safe_name=" + j["safe_name"])
print("good:", send("/avatar-safe", "me.png").get_json()["stored_as"])
Output:
bad : ../../etc/cron.d/evil.sh
safe: 400 type not allowed ext=sh safe_name=etc_cron.d_evil.sh
good: me.png
The attacker uploads a file named ../../etc/cron.d/evil.sh. The naive endpoint keeps that name verbatim, so a later f.save(os.path.join(UPLOAD_DIR, name)) would resolve out of the upload directory and drop a shell script into a system directory that runs jobs on a schedule -- a direct path from "upload an avatar" to "run my code on your server." The hardened endpoint first calls secure_filename, which flattens the name to etc_cron.d_evil.sh with the traversal gone, then sees the sh extension is not in the allowlist and returns 400. A genuine me.png sails through and is stored under its safe name.
The design flaw is an unrestricted file upload, and it has two independent teeth. The first is path traversal: because the code builds a storage path from an untrusted filename, the client chooses where the write lands. The second is the missing type check: even a name with no slashes, like shell.php dropped into a directory the web server will execute, turns an upload form into remote code execution. Neither secure_filename alone nor an extension allowlist alone is sufficient -- you need both, plus a size cap via MAX_CONTENT_LENGTH, storage outside the web root (or on separate object storage), and ideally a server-generated name so the user never controls the filename at all. The underlying lesson repeats the analogy: the filename, the content type, and the bytes all came from the customer, and every one of them is a claim to be verified, never a fact to be obeyed.
Common Mistakes
- Reading form fields from
request.args(or the reverse). A POSTed form lives inrequest.form; query parameters live inrequest.args. Read from the wrong container and every value comes back empty or defaulted, with no error to hint why. Match the container to how the data was actually sent.
- Using
.geton a field that can repeat. For checkbox groups, multi-selects, or repeated query parameters,.getsilently returns only the first value and discards the rest. Use.getlistwhenever the field could legitimately appear more than once.
- Assuming request values are already typed. Everything in
argsandformis a string:request.args.get("page")is"2", not2. Convert explicitly withint(...)inside atry/except, and reject bad input, rather than letting"abc"blow up deep in your code.
- Indexing with
[]for optional fields.request.form["email"]raises a 400BadRequestwhen the key is missing, which is fine for truly required fields but surprising for optional ones. Use.get("email", default)when absence is legitimate, and let[]stand only where the field is mandatory.
- Saving an upload under the client's filename.
f.save(os.path.join(UPLOAD_DIR, f.filename))lets a name like../../etc/passwdescape the directory. Always run the name throughsecure_filename, and prefer a server-generated name so the user never controls the path.
- Trusting the client's content type or extension to decide the file kind. The
Content-Typeheader and the.pngon the end of a name are both attacker-controlled. Validate against an allowlist and, for anything that matters, sniff the actual bytes; never route or execute a file based on its claimed type.
- Omitting
MAX_CONTENT_LENGTH. Without a configured size cap, a single upload can be gigabytes, exhausting memory or disk -- a trivial denial of service. Setapp.config["MAX_CONTENT_LENGTH"]so oversized requests are rejected before they are buffered.
- Reading security-relevant fields from
request.values. Becauserequest.valueslets the query string override the form, a caller who can only influence the URL may inject a value your code believes came from the body. Read such fields from the specific container you intend.
- Expecting
request.formto hold a JSON body. An API client that sendsapplication/jsonpopulatesrequest.json/request.get_json(), notrequest.form, which stays empty. Read JSON from the JSON accessor, and useget_json(silent=True)when a malformed body should be handled rather than raising.
Best Practices
- Read from the container that matches the channel. Use
request.argsfor query parameters,request.formfor submitted forms,request.filesfor uploads, andrequest.get_json()for JSON bodies. Reserverequest.valuesfor the rare case where you truly accept a field from either place.
- Treat every incoming value as an untrusted string. Convert types explicitly, validate ranges and formats, and reject what fails. A validation library or schema (such as Pydantic or a Flask form library) makes this systematic instead of ad hoc.
- Use
.getlistfor anything that can repeat. Model multi-valued fields as lists from the start so a second checkbox or a repeated parameter never silently vanishes.
- Sanitize and regenerate upload filenames. Pass names through
secure_filename, and prefer storing files under a name you generate (a UUID or database id) with the original kept only as a display label.
- Validate upload type by allowlist, not by the client's claim. Decide which extensions and media types you accept, check against that list, and for sensitive cases inspect the file's actual content rather than trusting the header.
- Cap request and upload size. Set
MAX_CONTENT_LENGTHso oversized bodies are refused early, protecting memory and disk from both accidents and abuse.
- Store uploads outside the web root. Keep user files in a directory the server will never execute or serve directly, and hand them back through a controlled route that checks permissions, so an uploaded script can never run.
- Return clear validation errors. When input is missing or malformed, respond with a 400 and a message that names the problem, so clients (and your future self) can see what was wrong instead of guessing at a generic failure.
Practice Exercises
- Build a
/searchroute that readsq(a string, default empty) andpage(convert to anint, default 1, and return a 400 if it is not a valid number). Using the test client, request it with?q=flask&page=3, with no query at all, and with?page=abc, and confirm the third returns 400 while the first two return the parsed values. Explain why the conversion cannot be skipped.
- Write a
/filterroute that accepts a repeatabletagparameter and an optionalsortparameter, and returns the list of tags plus the chosen sort. Test it with three tags and no sort, one tag andsort=price, and no parameters, verifying that the tag list is[]rather thanNonewhen absent. State which method you used to readtagand why.getwould be wrong.
- Implement
/uploadthat accepts a file field nameddoc, rejects anything whose sanitized extension is not in{"txt", "csv"}with a 400, and otherwise returns thesecure_filenameresult. Usingio.BytesIO, test it withnotes.txt(expect success),../../evil.sh(expect a 400 and confirm the traversal is stripped), and a missing file (handle it without a 500). Describe the two separate protections your code applies.
- Create a
/mergeroute that reads a fieldmodefromrequest.valuesand also reports where it came from by checkingrequest.argsandrequest.formseparately. POST to it withmodein only the form, then withmodein both the query string and the form, and confirm that the query value wins the second time. Explain the security risk of reading an authorization-related field fromrequest.values.