Flask Request Handling: The Mailroom of Your Web App π¬
The Big Picture
Imagine your Flask app is a friendly mailroom. Every time someone visits your website or sends data, theyβre delivering a package (request). Your job? Open the package, see whatβs inside, and respond!
The request object is your mailroom assistantβit knows everything about every package that arrives.
1. The Request Object: Your Mailroom Assistant π¦
When someone visits your Flask app, Flask creates a special helper called request. Think of it as a robot assistant that catches every incoming package and tells you:
- βWho sent this?β
- βWhatβs inside?β
- βHow was it delivered?β
How to Get Your Assistant
from flask import Flask, request
app = Flask(__name__)
@app.route('/hello')
def hello():
# request is now available!
# It knows everything about
# the incoming package
return "Package received!"
Simple Analogy:
request = A smart assistant who reads every letter before you do and can answer ANY question about it.
2. Query Parameters: Notes Written on the Package π·οΈ
Sometimes, the sender writes notes on the outside of the package. In web terms, these are query parametersβthe stuff after the ? in a URL.
Example URL
/search?name=pizza&city=rome
Here, name=pizza and city=rome are notes on the package.
How to Read These Notes
@app.route('/search')
def search():
# Get single value
name = request.args.get('name')
# Returns: 'pizza'
# Get with default if missing
city = request.args.get('city', 'unknown')
# Returns: 'rome'
# Get all values (if same key)
tags = request.args.getlist('tag')
# URL: ?tag=hot&tag=new
# Returns: ['hot', 'new']
return f"Searching {name} in {city}"
Quick Memory Trick π§
URL has a QUESTION? β Use request.ARGS
?name=value β request.args.get('name')
3. Form Data: Opening the Package π
When someone fills out a form (like a contact form) and clicks submit, the data comes inside the package, not written on it.
HTML Form Example
<form method="POST" action="/contact">
<input name="email" type="email">
<input name="message" type="text">
<button>Send</button>
</form>
Reading Form Data in Flask
@app.route('/contact', methods=['POST'])
def contact():
# Get form field
email = request.form.get('email')
message = request.form.get('message')
# With default value
phone = request.form.get('phone', 'Not given')
return f"Thanks, {email}!"
The Golden Rule π
Form submitted β request.form
URL with ? β request.args
4. JSON Data: The Fancy Gift Box π
Modern apps often send data as JSONβa neat, organized way to pack information. Think of it as a gift box with labeled compartments.
What JSON Looks Like
{
"username": "alex",
"age": 25,
"hobbies": ["coding", "music"]
}
Reading JSON in Flask
@app.route('/api/user', methods=['POST'])
def create_user():
# Get JSON data as dictionary
data = request.get_json()
# Now access like a dictionary!
username = data['username']
age = data['age']
hobbies = data['hobbies']
return {"status": "User created!"}
Important Notes β οΈ
# Silent mode - returns None if no JSON
data = request.get_json(silent=True)
# Force mode - tries even if
# Content-Type header is wrong
data = request.get_json(force=True)
5. Request Headers: The Shipping Label π·οΈ
Every package has a shipping label with extra info: who sent it, what type of content, etc. These are headers.
Common Headers
| Header | What It Tells You |
|---|---|
Content-Type |
What kind of data (JSON, form, etc.) |
User-Agent |
What browser/device sent this |
Authorization |
Login credentials |
Accept |
What format they want back |
Reading Headers
@app.route('/info')
def info():
# Get specific header
content_type = request.headers.get(
'Content-Type'
)
# Get user's browser info
browser = request.headers.get(
'User-Agent'
)
# Get auth token
token = request.headers.get(
'Authorization'
)
return f"Your browser: {browser}"
Pro Tip π‘
Headers are case-insensitive:
# Both work the same!
request.headers.get('Content-Type')
request.headers.get('content-type')
6. File Uploads: Special Delivery! π
Sometimes users want to send filesβphotos, documents, etc. These need special handling!
HTML Form for Files
<form method="POST"
action="/upload"
enctype="multipart/form-data">
<input type="file" name="photo">
<button>Upload</button>
</form>
Super Important: You MUST add enctype="multipart/form-data" or files wonβt work!
Receiving Files in Flask
from werkzeug.utils import secure_filename
@app.route('/upload', methods=['POST'])
def upload():
# Get the file
photo = request.files.get('photo')
# Check if file exists
if photo:
# Make filename safe
safe_name = secure_filename(
photo.filename
)
# Save it!
photo.save(f'./uploads/{safe_name}')
return "File uploaded!"
return "No file received"
7. Request Files Handling: The Complete Guide π
Letβs dive deeper into handling files like a pro!
File Object Properties
@app.route('/upload', methods=['POST'])
def upload():
file = request.files.get('document')
if file:
# Original filename
name = file.filename
# Example: "my photo.jpg"
# Content type
mime = file.content_type
# Example: "image/jpeg"
# Read raw bytes
data = file.read()
# Get file size (after read)
size = len(data)
return f"Got {name}, {size} bytes"
Multiple File Upload
<input type="file"
name="photos"
multiple>
@app.route('/gallery', methods=['POST'])
def gallery():
# Get list of all files
photos = request.files.getlist('photos')
saved = []
for photo in photos:
if photo.filename:
safe = secure_filename(
photo.filename
)
photo.save(f'./gallery/{safe}')
saved.append(safe)
return f"Saved {len(saved)} photos!"
Safety Checklist β
import os
ALLOWED = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() \
in ALLOWED
@app.route('/safe-upload', methods=['POST'])
def safe_upload():
file = request.files.get('image')
# Check 1: File exists?
if not file or file.filename == '':
return "No file!", 400
# Check 2: Allowed type?
if not allowed_file(file.filename):
return "Bad file type!", 400
# Check 3: Safe filename
filename = secure_filename(file.filename)
# Save safely
file.save(f'./uploads/{filename}')
return "Success!"
The Complete Request Flow π
graph TD A[User Sends Request] --> B{What Kind?} B -->|URL with ?| C[request.args] B -->|Form Submit| D[request.form] B -->|JSON API| E[request.get_json] B -->|File Upload| F[request.files] G[request.headers] --> H[Always Available] C --> I[Your Flask Code] D --> I E --> I F --> I H --> I
Quick Reference Table π
| Data Type | Where It Comes From | How to Access |
|---|---|---|
| Query params | URL ?key=value |
request.args.get('key') |
| Form data | HTML form POST | request.form.get('field') |
| JSON | API request body | request.get_json() |
| Headers | Request metadata | request.headers.get('Name') |
| Files | File input field | request.files.get('name') |
You Did It! π
You now understand how Flask handles every type of request data:
- β
Query Parameters β Notes on the package (
request.args) - β
Form Data β Inside the box (
request.form) - β
JSON Data β Fancy labeled compartments (
request.get_json()) - β
Headers β Shipping label (
request.headers) - β
Files β Special deliveries (
request.files)
Remember: The request object is your trusty mailroom assistant. It catches everything and organizes it for you. Just ask it the right questions!
βEvery web request is just a package waiting to be opened. Flask makes sure you have the right tools to handle them all!β π¬