Flask is a lightweight web framework for Python that is designed to make getting started quick and easy, with the ability to scale up to complex applications. In this section, we will cover the basics of Flask, including setting up a Flask application, routing, templates, and handling requests.

Table of Contents

Introduction to Flask

Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.

Key Features of Flask:

  • Lightweight and modular: Flask is designed to be simple and easy to extend.
  • Built-in development server and debugger: Flask comes with a built-in server and debugger.
  • RESTful request dispatching: Flask supports RESTful request dispatching.
  • Jinja2 templating: Flask uses Jinja2 as its templating engine.
  • Support for secure cookies: Flask supports client-side sessions using secure cookies.

Setting Up a Flask Application

Step 1: Install Flask

First, you need to install Flask. You can do this using pip:

pip install Flask

Step 2: Create a Basic Flask Application

Create a new Python file, for example, app.py, and add the following code:

from flask import Flask

app = Flask(__name__)

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

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

Explanation:

  • Import Flask: Import the Flask class from the flask module.
  • Create an instance of the Flask class: This instance will be our WSGI application.
  • Define a route: Use the @app.route decorator to bind a function to a URL.
  • Run the application: Use app.run() to run the application.

Running the Application

Run the application by executing the following command in your terminal:

python app.py

You should see output indicating that the server is running, and you can visit http://127.0.0.1:5000/ in your web browser to see the "Hello, Flask!" message.

Routing in Flask

Routing in Flask is simple and intuitive. You define routes using the @app.route decorator.

Example:

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

Dynamic Routes:

You can also create dynamic routes by adding variable parts to the URL:

@app.route('/user/<username>')
def show_user_profile(username):
    return f'User {username}'

Explanation:

  • Static Route: The /hello route is a static route that always returns "Hello, World!".
  • Dynamic Route: The /user/<username> route is a dynamic route that captures the value in the URL and passes it to the show_user_profile function.

Templates in Flask

Flask uses the Jinja2 templating engine to render HTML templates.

Step 1: Create a Template

Create a folder named templates in the same directory as your app.py file. Inside the templates folder, create a file named index.html with the following content:

<!doctype html>
<html>
<head>
    <title>Hello, Flask!</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

Step 2: Render the Template

Modify your app.py file to render the template:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html', name="Flask")

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

Explanation:

  • render_template: Import the render_template function from Flask.
  • Render the template: Use render_template to render the index.html template and pass the name variable to it.

Handling Requests and Responses

Flask provides several ways to handle requests and responses.

Handling GET and POST Requests:

You can specify the methods allowed for a route using the methods parameter:

@app.route('/submit', methods=['GET', 'POST'])
def submit():
    if request.method == 'POST':
        return "Form Submitted"
    return "Submit Form"

Accessing Request Data:

You can access request data using the request object:

from flask import request

@app.route('/submit', methods=['POST'])
def submit():
    data = request.form['data']
    return f"Data received: {data}"

Explanation:

  • methods: Specify the HTTP methods allowed for the route.
  • request.method: Check the HTTP method of the request.
  • request.form: Access form data sent in a POST request.

Practical Exercises

Exercise 1: Create a New Route

Create a new route /greet/<name> that returns a greeting message with the provided name.

Solution:

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

Exercise 2: Create a Form

Create a form that allows users to submit their name and displays a greeting message.

Solution:

  1. Create a template form.html:

    <!doctype html>
    <html>
    <head>
        <title>Greeting Form</title>
    </head>
    <body>
        <form action="/greet" method="post">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name">
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
    
  2. Modify app.py:

    from flask import Flask, render_template, request
    
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return render_template('form.html')
    
    @app.route('/greet', methods=['POST'])
    def greet():
        name = request.form['name']
        return f'Hello, {name}!'
    
    if __name__ == '__main__':
        app.run(debug=True)
    

Summary

In this section, we covered the basics of the Flask framework, including setting up a Flask application, routing, templates, and handling requests and responses. We also provided practical exercises to reinforce the learned concepts. In the next section, we will delve deeper into building REST APIs with Flask.

Python Programming Course

Module 1: Introduction to Python

Module 2: Control Structures

Module 3: Functions and Modules

Module 4: Data Structures

Module 5: Object-Oriented Programming

Module 6: File Handling

Module 7: Error Handling and Exceptions

Module 8: Advanced Topics

Module 9: Testing and Debugging

Module 10: Web Development with Python

Module 11: Data Science with Python

Module 12: Final Project

© Copyright 2024. All rights reserved