0
0
Flaskframework~5 mins

How Flask processes HTTP requests

Choose your learning style9 modes available
Introduction

Flask processes HTTP requests to let your web app respond to users. It listens for requests and sends back the right answers.

When you want to build a simple website that shows different pages.
When you need to handle form submissions from users.
When you want to create an API that other programs can talk to.
When you want to respond differently based on the URL or request method.
When you want to serve files or data based on user requests.
Syntax
Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/path', methods=['GET', 'POST'])
def handler():
    # code to handle request
    return 'response'

if __name__ == '__main__':
    app.run()

@app.route tells Flask which URL to listen to.

The methods list tells Flask which HTTP methods to accept (like GET or POST).

Examples
This example handles a GET request to the home page and returns a greeting.
Flask
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, world!'
This example handles a POST request with form data and responds with a message including the submitted name.
Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit():
    data = request.form.get('name')
    return f'Hello, {data}!'
Sample Program

This Flask app shows how it processes different HTTP requests:

  • GET request to '/' returns a welcome message.
  • GET request to '/greet/<name>' returns a personalized greeting.
  • POST request to '/data' reads JSON data and responds with the message received.
Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    return 'Welcome to the homepage!'

@app.route('/greet/<name>')
def greet(name):
    return f'Hello, {name}!'

@app.route('/data', methods=['POST'])
def data():
    info = request.json
    return f'Received: {info.get("message", "No message")}'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Flask matches the URL path to the function decorated with @app.route.

The request object holds all info about the incoming HTTP request.

Flask automatically converts the function's return value into an HTTP response.

Summary

Flask listens for HTTP requests and matches them to functions using routes.

Each route can handle different HTTP methods like GET or POST.

The request object lets you access data sent by the user.