Request Handling

Loading concept...

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:

  1. βœ… Query Parameters β€” Notes on the package (request.args)
  2. βœ… Form Data β€” Inside the box (request.form)
  3. βœ… JSON Data β€” Fancy labeled compartments (request.get_json())
  4. βœ… Headers β€” Shipping label (request.headers)
  5. βœ… 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!” πŸ“¬

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.