Learn Flask · 4/15

Request and Response Handling: The Core of Web Interaction

9 min read

Hello there, future Flask developer! 🧙‍♂️

Welcome to the central station of your web application. Everything that comes in and goes out of your app passes through here. We're talking about Requests and Responses. Think of your Flask app as a very organized librarian. A user comes with a request slip (the Request), and the librarian finds the exact book and hands it back (the Response). Simple, right? Let's break down how you can be the best librarian on the web.


1. The Request Object: Accessing Form Data, Queries, and Headers 📥

First things first, what is a "request"? Whenever a user visits a URL, fills out a form, or clicks a button on your website, their browser sends a package of information to your server. In Flask, all of this information is neatly bundled into a global object called request. You can import it directly from the flask library.

The problem it solves is fundamental: it's the only way for your server-side Python code to know what the user wants. What page are they asking for? What did they type into the search bar? Are they logged in? The request object holds all the clues.

To use it, you just import it:
from flask import Flask, request

Let's look at the most common things you'll pull out of this magic box.

Accessing Form Data (request.form)

When a user submits a form (like a login or a contact form), the data usually arrives via a POST request. This data is stored in the request.form dictionary.

Imagine you have a simple HTML form:

html
<form action="/login" method="post">
    <label>Username:</label>
    <input type="text" name="username">
    <label>Password:</label>
    <input type="password" name="password">
    <button type="submit">Submit</button>
</form>

In your Flask app, you can grab the submitted values like this:

python
from flask import Flask, request

app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
    # Using request.form.get() is safer than request.form['key']
    # because it returns None if the key is missing, avoiding a crash.
    username = request.form.get('username')
    password = request.form.get('password')

    if username == "admin" and password == "secret":
        return f"Welcome, {username}!"
    else:
        return "Invalid credentials."

Industry Practice: Always use .get('key') to access form data. It prevents your app from throwing a KeyError and crashing if the form field is unexpectedly missing. You can even provide a default value, like request.form.get('username', 'Guest').

Accessing Query Parameters (request.args)

Query parameters (or query strings) are the bits you see at the end of a URL after a ?. They are used to pass extra data, often for searching, sorting, or filtering.
https://example.com/search?q=flask&sort=newest

Here, q and sort are the query parameters. Flask stores these in the request.args dictionary.

python
from flask import Flask, request

app = Flask(__name__)

@app.route('/search')
def search():
    query = request.args.get('q')
    sort_by = request.args.get('sort', 'relevance') # with a default value

    if not query:
        return "Please enter a search term."

    return f"<h1>Searching for: '{query}'</h1><p>Sorting by: {sort_by}</p>"

This is super useful for building APIs or pages where the content changes based on these optional parameters.

Accessing Headers (request.headers)

HTTP headers are extra pieces of information sent with both requests and responses. They contain metadata like the browser type (User-Agent), the data format being sent (Content-Type), and authentication tokens. You can access them via request.headers.

python
from flask import Flask, request

app = Flask(__name__)

@app.route('/who-are-you')
def who_are_you():
    user_agent = request.headers.get('User-Agent')
    return f"It looks like you are using: {user_agent}"

You won't access headers as often as form or query data, but they are crucial for things like authentication and understanding the client's capabilities.


2. The Response Object: Customizing Status Codes and Headers 📤

Just as your app receives requests, it must send responses. Usually, you just return a string of HTML, and Flask handles the rest. But what if you need more control? What if you want to send back a different status code or add your own custom headers? That's when you need to create a Response object.

The problem this solves is the need for more expressive communication with the browser. Sometimes "OK" (the default 200 status code) isn't enough. You might need to say "Created" (201), "Not Found" (404), or add a custom header for caching.

To get full control, you can use the make_response function.

Customizing Status Codes

HTTP status codes are three-digit numbers that tell the browser the result of its request. Everyone knows 404 (Not Found), but there are many others!

  • 200 OK: Everything is fine.
  • 201 Created: You successfully created something (e.g., a new user).
  • 400 Bad Request: The user sent something your server can't understand.
  • 403 Forbidden: You know who the user is, but they aren't allowed to see this.

Here’s how to set one:

python
from flask import Flask, make_response, jsonify

app = Flask(__name__)

@app.route('/users', methods=['POST'])
def create_user():
    # Pretend we created a user in the database...
    new_user = {"id": 1, "username": "new_user"}

    # Create a JSON response with a 201 status code
    response = make_response(jsonify(new_user), 201)
    return response

@app.route('/secret-data')
def secret_data():
    # You can also return a tuple: (body, status_code)
    return "You are not allowed to see this!", 403

Funny Fact: There's a joke status code, 418 I'm a teapot. It was defined as an April Fools' joke in 1998 and is a delightful way to say "I refuse to brew coffee because I am a teapot."

Customizing Headers

Just like with the request object, you can add headers to your response. This is often used to set the Content-Type or to add caching instructions.

python
from flask import Flask, make_response

app = Flask(__name__)

@app.route('/custom')
def custom_response():
    response = make_response("This is a custom response!")
    response.status_code = 202 # Accepted
    response.headers['X-My-Custom-Header'] = 'Hello from the server!'
    response.headers['Content-Type'] = 'text/plain'
    return response

This gives you fine-grained control over exactly what your server sends back to the browser.


3. Redirects and Errors: Navigating Users and Using abort() 🗺️

Sometimes, you don't want to show a page at all. You either need to send the user somewhere else or stop everything because of an error.

Redirecting Users (redirect())

Problem: After a user successfully logs in or submits a form, you don't want them to stay on the form page. You want to send them to their dashboard or a "success" page. The redirect function is built for this.

It tells the browser, "Hey, the thing you're looking for is over here now."

python
from flask import Flask, redirect, url_for, request

app = Flask(__name__)

@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        # Pretend we checked the user's password
        username = request.form.get('username')
        # Redirect to the user's profile page
        return redirect(url_for('profile', username=username))
    # If it's a GET request, show the login form
    return '''
        <form method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/profile/<username>')
def profile(username):
    return f'<h1>Welcome to your profile, {username}!</h1>'

Industry Practice: Notice the url_for() function. Always use it to build URLs for your routes instead of hardcoding them ('/profile/...'). This way, if you ever change the URL of a route, your redirects won't break.

Aborting Requests (abort())

Problem: What if a user requests a resource that doesn't exist, or they try to do something they don't have permission for? You need to stop the request immediately and return an appropriate error code. The abort() function does exactly that.

python
from flask import Flask, abort

app = Flask(__name__)

# A dictionary of users for our example
USERS = {
    "1": {"username": "admin"},
    "2": {"username": "guest"},
}

@app.route('/user/<id>')
def get_user(id):
    if id not in USERS:
        # Stop everything and show a 404 Not Found page
        abort(404)
    return f"User found: {USERS[id]['username']}"

# You can even create custom error pages
@app.errorhandler(404)
def page_not_found(error):
    return "Oops! We couldn't find that page. Sorry!", 404

When you call abort(404), Flask stops executing your view function and shows the user a generic 404 error page. You can customize these error pages using the @app.errorhandler() decorator to make your app more user-friendly.


4. Handling File Uploads Securely 📂

Allowing users to upload files is a powerful feature, but also a huge security risk. An attacker could upload a malicious script, a virus, or fill up your server's storage. Therefore, handling uploads requires extra care.

Problem: How do you let users upload files (like a profile picture) without exposing your server to attack?

Flask makes the basic process easy via request.files, but you must add security checks.

Key Security Steps:

  1. Sanitize the filename: Never trust a filename from a user. They could submit something like ../../../../.bashrc to try and overwrite critical system files.
  2. Validate the file type: Don't just check the extension (.jpg). Check the actual content type (MIME type) to ensure a malicious file isn't disguised as an image.
  3. Limit the file size: Prevent users from uploading gigantic files that could crash your server.

The werkzeug library (which Flask is built on) provides a handy function called secure_filename() to help with step 1.

Here is a secure-by-default example:

python
import os
from flask import Flask, request, redirect, url_for, flash
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB limit
app.secret_key = 'super-secret-key' # Needed for flash messages

# Helper function to check for allowed file types
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)

        file = request.files['file']

        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            # THIS IS THE CRUCIAL STEP!
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('upload_file', name=filename))

    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

Industry Standard: In a real-world application, you would almost never save uploaded files directly to your web server's filesystem. You would upload them to a dedicated, secure cloud storage service like Amazon S3, Google Cloud Storage, or Azure Blob Storage. This is more scalable, secure, and reliable.


Further Reading 📚

Challenge

Challenge: Build a Product Review Submission Endpoint

Your task is to create a Flask application that handles product review submissions. You will need to implement two routes: one to process the incoming review data and another to serve as a 'thank you' page after a successful submission.

Route 1: /submit-review

  1. This route must only accept POST requests.
  2. It needs to extract the following data from the incoming request:
    • product_id (from form data)
    • rating (from form data)
    • review_text (from form data)
  3. It must perform the following server-side validation on the received data:
    • product_id and review_text must not be empty or missing.
    • The rating must be a whole number between 1 and 5, inclusive.
  4. If any validation check fails, the application must immediately terminate the request with a 400 Bad Request HTTP status code.
  5. If the submission is valid, the application must issue a redirect to the /thank-you page.
  6. Crucially, this redirect response must include a custom HTTP header: X-Review-Status with a value of processed.

Route 2: /thank-you

  1. This route should be accessible via a GET request.
  2. It should simply return the string "Thank you for your review!" as the response body.

Expected result

Your final code should contain a complete Flask application with the two specified routes (/submit-review and /thank-you).

  • The submit_review function must correctly use the request object to access request.form for product_id, rating, and review_text.
  • It must implement validation logic that checks for the presence of required fields and ensures the rating is within the valid range (1-5). Remember to handle the data type conversion for the rating.
  • The abort(400) function must be called if any validation condition is not met.
  • For a valid submission, your code must use redirect(url_for('thank_you_page')) to generate the redirect response.
  • You must correctly create or modify the response object to add the custom header X-Review-Status: processed. Using make_response() is a common way to achieve this.
  • The thank_you_page function must be implemented to return the specified confirmation string.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.