Introduction en 10 minutes au framework web Flask pour Python

Posted by


Flask is a popular web framework for Python that allows you to build web applications quickly and easily. In this tutorial, we will learn about Flask and how to get started with this framework in just 10 minutes.

Step 1: Installing Flask

The first step is to install Flask on your system. You can simply use pip, the Python package installer, to install Flask. Open your terminal and type the following command:

pip install Flask

This will install Flask and all its dependencies on your system.

Step 2: Creating a simple Flask app

Now that Flask is installed, let’s create a simple Flask app. Open your favorite text editor and create a new file called app.py. In this file, we will write a simple Flask app that just displays "Hello, world!" when you visit the root URL.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, world!'

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

Save this file and run it by typing the following command in your terminal:

python app.py

This will start a development server at http://127.0.0.1:5000/. Visit this URL in your browser, and you should see "Hello, world!" displayed on the screen.

Step 3: Routing

In Flask, routing is the mechanism that maps URLs to functions in your code. In the above example, we used the @app.route('/') decorator to tell Flask that the hello_world function should be called when the root URL is visited.

You can create more routes by simply adding more functions and decorators. For example:

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

@app.route('/contact')
def contact():
    return 'Contact us at contact@example.com'

Step 4: Rendering templates

Flask allows you to render HTML templates easily. Create a new directory in your project called templates, and create a new file called index.html inside it with the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to my website!</h1>
</body>
</html>

Now, modify your Flask app to render this template:

from flask import Flask, render_template

app = Flask(__name__)

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

Visit the root URL again in your browser, and you should see the content of the index.html template displayed on the screen.

Step 5: Handling form data

Flask makes it easy to handle form data in your applications. Create a new file called form.html inside the templates directory with the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Form</title>
</head>
<body>
    <h1>Fill out the form</h1>
    <form action="/submit" method="post">
        <input type="text" name="name" placeholder="Your name">
        <input type="email" name="email" placeholder="Your email">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Now, modify your Flask app to handle the form submission:

from flask import Flask, render_template, request

app = Flask(__name__)

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

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    email = request.form['email']
    return f'Thank you, {name}, for submitting your email ({email})'

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

Visit the root URL in your browser, fill out the form, and submit it. You should see a thank you message with the submitted data displayed on the screen.

Conclusion

In this tutorial, we learned how to get started with Flask, a powerful web framework for Python. We created a simple web app, learned about routing, rendering templates, and handling form data. Flask is a versatile framework that can be used to build a wide range of web applications, from simple websites to complex APIs. I hope this tutorial has given you a good introduction to Flask, and I encourage you to explore further and build your own projects with this framework. Happy coding!

0 0 votes
Article Rating
24 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@IbrahimaMamadouBa
1 month ago

vous parlez trés bien comme la voix de NOTA BENE

@chrisder1814
1 month ago

bonjour est-ce que tu pourrais m'aider à comprendre comment utiliser les API avec chatg0t
j'ai cru comprendre qu'il y a deux manières de faire

@cgc2300
1 month ago

Bonjour

pour résumer mes messages précédents et essayer de comprendre ce que je peux faire avec les api

sur le site de make 'il y a très peu de détails, je veux dire seulement quelques mots pour décrire chacun des déclencheurs de chaque application,

Il n'existe pas un générateur de scénario make?

Je me suis rendu compte que chatgpt est capable de raisonner en nous écrivant une histoire ou une recette de cuisine sur mesure

J'ai pensé qu'il pourrait également raisonner en me donnant des exemples d'utilisation de make, des scénarios sur mesure en fonction de mes objectifs

@MsVideoenligne
1 month ago

Hello, moi je suis là pour commencer à apprendre 🙂 merci

@cgc2300
1 month ago

salut et merci
le problème c'est que je n'ai carrément pas le niveau pour comprendre

@fouadhellal5346
1 month ago

Après un an de travail de projets avec Django, j'ai eu le courage ce matin de découvrir flask grâce à vous, pardon, toi* 🤣

@imazian9752
1 month ago

👍👍👍👍

@varanbo
1 month ago

pour un projer j'au un site sur un Raspberry pi et j'ai également un moteur connecter. est ce que on peut utiliser flask pour commander le moteur depuis l'html

@Ne21317
1 month ago

Est qu'est un autre façon pour afficher la page web sans arriver a terminal

@Ne21317
1 month ago

Donner la première commande qu'est vous êtes utilisé avant virtuelenv

@abdulbouraa4529
1 month ago

Bonjour, avant tout merci pour la vidéo c'était très claire !!
Pour ma part je me suis tourné vers Flask afin d'apprendre à déployer mes modèles de machine learning. Je pense continuer l'utiliser pour la suite de mes projets.

@annonymous9459
1 month ago

Bonjour Sergio ! J'utilise Flask parce qu'il a la réputation d'être plus abordable que Django quand on débute. De ce que j'ai lu, les dev plus expérimentés préfèrent Django.
Et merci à toi pour ce tuto et tes explications ligne par ligne, c'est tellement plus clair maintenant !

@moiseprosper375
1 month ago

Maintenant fais nous un crud et les sessions avec flask ❤

@naofalamoussa8935
1 month ago

Grâce à toi j’ai tout compris. Grand merci à toi
Faut absolument continuer 🙏🙏🙏

@user-gz4vh9vl8j
1 month ago

Bonjour Je serais très intéressé pour faire du REST API avec Flask. Merci

@tigzeryan9185
1 month ago

Bonjour, une très bonne vidéo, j'aimerais a partir de Flask gérer un fichier texte et insérer du texte récupérer grâce à un web services si tu peux faire un Petit point sur sa mercis chef

@gyrelmso7782
1 month ago

On attend la suite bien sur !

@antoinebosche6069
1 month ago

Super ton contenu ! Très quali ça fait plaisir 🚀

@garciamukoko7739
1 month ago

pas mal votre explication , mais comment evite le warning

@keitaro7918
1 month ago

Utilisateur django , pour l’instant je ne vois pas l’intérêt de flask par rapport à django ( il y en a sûrement…😅)