Python libraries and frameworks Flask

Flask is a popular Python web framework used for building web applications. Flask is lightweight and flexible, and is designed to be easy to use and learn.

Here are some key features and examples of how to use Flask:

## Routing

The core of Flask is its routing system, which allows you to map URLs to Python functions. Here’s an example of a simple Flask app with a single route:

python
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

In this example, we define a Flask app and a single route that maps the root URL (`”/”`) to a Python function called `hello()`. When the user visits the root URL, Flask will call the `hello()` function and return the string `”Hello, World!”`.

## Templates

Flask also provides a way to use templates to generate dynamic HTML content. Here’s an example of how to use a template to render a dynamic greeting:

python
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/greeting/")
def greeting(name):
    return render_template("greeting.html", name=name)

In this example, we define a new route that takes a parameter `name`. When the user visits a URL like `/greeting/Alice`, Flask will call the `greeting()` function and pass in the value `”Alice”` as the `name` parameter. The `greeting()` function then uses a template called `greeting.html` to generate the dynamic HTML content.

## Forms

Flask also provides a way to handle user input using HTML forms. Here’s an example of how to define a form in HTML and handle the form submission in Flask:

python
from flask import Flask, render_template, request

app = Flask(__name__)

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

@app.route("/submit", methods=["POST"])
def submit():
    name = request.form.get("name")
    email = request.form.get("email")
    return f"Thanks for submitting the form, {name} ({email})!"

In this example, we define a new route that displays a form to the user. When the user submits the form, Flask will call the `submit()` function and extract the values of the `name` and `email` fields from the form data. The `submit()` function then uses these values to generate a response.

Overall, Flask is a powerful and flexible web framework for building web applications in Python, and is widely used in a variety of fields, including data science, education, and software development.