Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Flask Core Concepts | Introduction to Flask
Python Flask Basics and App Setup for Beginners

bookFlask Core Concepts

Glissez pour afficher le menu

Flask Core Concepts: Routes, Views, Templates, and Request Handling

Flask is a lightweight web framework for Python that makes it easy to build web applications. To understand how Flask works, it's important to learn about its core concepts: routes, views, templates, and request handling. These components work together to process web requests and generate responses for users.

1. Routes

A route is a URL pattern that is linked to a specific function in your Flask app. Routes tell Flask what code to execute when a user visits a particular web address. You define routes using the @app.route() decorator.

Example:

@app.route('/')
def home():
    return 'Welcome to my Flask app!'

In this example, when a user visits the root URL (/), the home function is called.

2. Views

A view is a Python function that returns the content (response) users see when they visit a route. Views can return simple text, HTML, or more complex responses. Each route is connected to a view function.

Example:

@app.route('/about')
def about():
    return 'This is the About page.'

Here, the about view returns a simple message for the /about route.

3. Templates

Templates allow you to separate the design (HTML) from your Python code. Flask uses the Jinja2 templating engine to render dynamic HTML pages. You can pass data from your views to templates, making your web pages interactive and customizable.

Example:

from flask import render_template

@app.route('/hello/<name>')
def hello(name):
    return render_template('hello.html', name=name)

In this example, hello.html is a template file that can display the user's name dynamically.

4. Request Handling

Flask handles HTTP requests (like GET, POST, etc.) sent by users. You can access request data (such as form inputs or query parameters) using Flask's request object.

Example:

from flask import request

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

Here, Flask processes a POST request and retrieves data sent from a form.


How These Components Work Together

When a user visits your Flask app:

  1. The browser sends a request to a specific URL.
  2. Flask matches the URL to a route and calls the associated view function.
  3. The view function may process data or interact with templates to generate a response.
  4. Flask sends the response (HTML, text, or other content) back to the user's browser.

By understanding these core concepts, you can start building Flask applications that handle web requests, render dynamic pages, and provide interactive user experiences.

Note
Key Flask Terms Explained

Route: A route is a URL pattern that Flask uses to map a web address (like /about) to a specific function in your code. Routes define how users interact with your application through different URLs.

View Function: A view function is a Python function that is called when its associated route is accessed. It contains the logic to process requests and return responses, such as HTML pages or data.

Template: A template is an HTML file (often with placeholders) that Flask fills with dynamic content before sending it to the user. Templates help separate your application’s logic from its presentation.

Request: The request represents all the information sent by the client (browser) to your Flask application, such as form data or URL parameters. Flask provides a request object to access this data and handle user input.

Together, these components allow Flask to receive a web request, process it using a view function, render a template if needed, and send a response back to the user.

1234567891011121314151617
# Import the Flask class from flask import Flask # Create a Flask application instance app = Flask(__name__) # Define a route and map it to the view function def hello(): return "<h1>Hello, Flask!</h1>" # The route() decorator tells Flask to trigger # the 'hello' function when '/' is requested app.route("/")(hello) # Run the app if this file is executed directly if __name__ == "__main__": app.run(debug=True)
copy
Routes
expand arrow

Explanation:

Routes in Flask define the URLs that your web application responds to. Each route is associated with a specific function (called a view function) that is executed when the route is accessed.

Example:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Flask!'

In this example, visiting http://localhost:5000/ will display "Hello, Flask!".

Views
expand arrow

Explanation:

A view in Flask is a Python function that returns the content to be displayed in the user's browser. Views are linked to routes, and they determine what response is sent back for a given request.

Example:

@app.route('/about')
def about():
    return 'About this site'

Here, the /about route is handled by the about view function.

Templates
expand arrow

Explanation:

Templates allow you to separate your Python code from the HTML that is sent to the client. Flask uses the Jinja2 templating engine to render dynamic HTML pages.

Example: Suppose you have a template file called hello.html:

<!-- templates/hello.html -->
<h1>Hello, {{ name }}!</h1>

In your Flask app:

from flask import render_template

@app.route('/hello/<username>')
def hello(username):
    return render_template('hello.html', name=username)

Visiting /hello/Alice would display "Hello, Alice!".

Request Handling
expand arrow

Explanation:

Flask makes it easy to access information about the current web request, such as form data, query parameters, and HTTP methods. This is managed through the request object.

Example:

from flask import request

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

Here, the /greet route accepts POST requests and retrieves the value of the name field from the submitted form data.

The Request-Response Cycle in Flask

Understanding the request-response cycle is crucial for building web applications with Flask. This cycle describes how a user's action in their browser (like visiting a URL or submitting a form) is processed by your Flask app and how a response is sent back to the browser.

1. The Browser Sends a Request

When a user enters a URL or clicks a link, their browser sends an HTTP request to your Flask application's server. This request contains information such as:

  • The requested URL path (e.g., /about)
  • The HTTP method (e.g., GET, POST)
  • Any submitted form data or query parameters

2. Flask Matches the Request to a Route

Flask examines the incoming request and tries to find a route that matches the URL path and HTTP method. Routes are defined in your Python code using the @app.route() decorator:

@app.route('/about')
def about():
    return 'About Page'

If a matching route is found, Flask calls the associated view function.

3. The View Function Handles the Request

The view function is responsible for processing the request. It can:

  • Access request data using the request object (from flask)
  • Interact with databases or perform other logic
  • Choose what content to return to the user

Example:

from flask import request

@app.route('/greet')
def greet():
    name = request.args.get('name', 'Guest')
    return f'Hello, {name}!'

4. Generating the Response

The view function returns a response. This can be:

  • A simple string (which will be sent as HTML)
  • A rendered HTML template
  • JSON data (for APIs)
  • A redirect or file download

Example with a template:

from flask import render_template

@app.route('/welcome')
def welcome():
    return render_template('welcome.html')

5. Flask Sends the Response Back

Flask takes the return value from your view function, builds an HTTP response, and sends it back to the browser. The browser then displays the result to the user.

Visual Overview

Browser  →  Flask Route  →  View Function  →  Response  →  Browser

Summary

  • Request: User action triggers a request to the Flask app.
  • Routing: Flask finds a matching route and calls the view function.
  • Processing: The view function handles the request and prepares a response.
  • Response: Flask sends the response back to the user's browser.

This request-response cycle is at the heart of every Flask web application.

question mark

In Flask, what is the main purpose of a view function?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 2

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 1. Chapitre 2
some-alt