Blueprint in Flask

Keywords: Python

Catalog

1. Overview of flask blueprint

The function is to separate the function from the main service. The blueprint has no run method

For example, you have a customer management system. At the beginning, there was only one function to view the customer list. Later, you added an add user module, then a del user module, and then an up user module. In this system, you can add

Four functions of viewing customers, modifying customers, adding customers and deleting customers are added into the customer management system as blueprints, so that a single application template is managed separately from the main server

2. A simple blueprint implementation

2.1 example 1:

manager.py file:

from flask import Flask, render_template
# Import the previously written blueprint module
from student_view import view_list

app = Flask(__name__)
app.debug = True

# Register the blueprint object in the blueprint module in the Flask object show in view list
app.register_blueprint(view_list.show)

if __name__ == '__main__':
    # Now there are no route and view functions written in the Flask object
    app.run()

The blueprint application separates the main service and creates a new student view folder to put the blueprint in a separate py file

Create a view list.py file:

from flask import Blueprint  # Import Blueprint blueprint module in Flask

show = Blueprint("sv", __name__)  # Instantiate a blueprint object


@show.route("/show_list")  # The route and view functions are added here as in the Flask object
def show_list():
    return "show_list"

web access:

  

2.2 example 2:

Contents in the s view.py file:

from flask import Blueprint  # Import Blueprint blueprint module in Flask
from flask import render_template

sv = Blueprint("sv",
               __name__,
               template_folder="sv_template",  # Each blueprint can create a set of template folder for itself. If not, templates in the project directory will be shared
               static_folder="sv_static"  # Static file directory can also be independent
               )  # Instantiate a blueprint object


@sv.route("/svlist")
def view_list():
    return render_template("svlist.html")

Content in svlist.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Hello ! I am sv_template
    <img src="/sv_static/123.png">
</body>
</html>

3. Blueprint to realize the addition, deletion, modification and search of student information

Use the Flask blueprint to modify the student information. The view structure is as follows:

  

3.1 view student information:

Create a student [Select folder:

Content in student [Select / stu] select.py file:

from flask import Blueprint
from flask import render_template
from student_data import STUDENT

ss_blueprint = Blueprint("ss_b", __name__, template_folder="html", static_folder="static")


@ss_blueprint.route("/s_list")
def s_list():
    return render_template("s_list.html", student=STUDENT)

Content in student [Select / HTML / S] list.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>List of students</title>
</head>
<body>
<table border="3xp">
    <thead>
    <tr>
        <td>ID</td>
        <td>name</td>
        <td>age</td>
        <td>gender</td>
        <td>options</td>
    </tr>
    </thead>
    <tbody>
    {% for foo in student %}
        <tr>
            <td>{{ foo.id }}</td>
            <td>{{ foo["name"] }}</td>
            <td>{{ foo.get("age") }}</td>
            <td>{{ foo.gender }}</td>
            <td> <a href="/s_update/{{ foo.id }}">modify</a> | <a href="/s_del?id={{ foo.id }}">delete</a> </td>
        </tr>
    {% endfor %}
    </tbody>
</table>
<a href="/s_add"> Add student </a>
</body>
</html>

3.2 student information update:

Create a student update folder:

Content in the student? Update / stu? Update.py file:

from flask import Blueprint
from flask import render_template
from flask import redirect
from flask import request
from student_data import STUDENT

s_update = Blueprint("s_update", __name__, template_folder="html", static_folder="static")


@s_update.route("/s_update/<int:nid>", methods=["GET", "POST"])
def s_update_view(nid):
    if request.method == "POST":
        stu_id = int(request.form["id"])
        stu_dic = {
            "id": stu_id,
            "name": request.form["name"],
            "age": request.form["age"],
            "gender": request.form["gender"]
        }

        for index, stu in enumerate(STUDENT):
            if stu["id"] == stu_id:
                STUDENT[index] = stu_dic

        return redirect("/s_list")

    for stu in STUDENT:
        if stu["id"] == nid:
            return render_template("s_update.html", student=stu)

    return render_template("s_update.html", student="")

Content in the student [update / HTML / S] update.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>List of students</title>
</head>
<body>
<form method="post">
    <input type="text" name="id" hidden value="{{ student.id }}"><br>
    Full name:<input type="text" name="name" value="{{ student.name }}"><br>
    Age:<input type="text" name="age" value="{{ student.age }}"><br>
    Gender:<input type="text" name="gender" value="{{ student.gender }}"><br>
    <input type="submit" value="Modify information">
</form>

</body>
</html>

3.3 increase of student information:

Create a student add folder:

Student? Add / stu? Add.py file:

from flask import Blueprint, redirect, render_template, request
from student_data import STUDENT

s_add = Blueprint("s_add", __name__, template_folder="html", static_folder="static")


@s_add.route("/s_add", methods=["POST", "GET"])
def s_add_view():
    if request.method == "POST":
        stu_dic = {
            "id": request.form.get("id"),
            "name": request.form.get("name"),
            "age": request.form.get("age"),
            "gender": request.form.get("gender")
        }
        STUDENT.append(stu_dic)

        return redirect("/s_list")
    else:
        return render_template("s_add.html")

Content in the student? Add / HTML / S? Add.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>List of students</title>
</head>
<body>
<form method="post">
    ID:<input type="text" name="id"> <br>
    Full name:<input type="text" name="name"><br>
    Age:<input type="text" name="age"><br>
    Gender:<input type="text" name="gender"><br>
    <input type="submit" value="Add student">
</form>

</body>
</html>

3.4 main server for managing student information:

Create a student folder:

**Content in student init.py file:**

from flask import Flask
from student_select import stu_select
from student_add import stu_add
from student_update import stu_update


def create_app():
    app = Flask(__name__)  # type:Flask

    app.register_blueprint(stu_select.ss_blueprint)
    app.register_blueprint(stu_add.s_add)
    app.register_blueprint(stu_update.s_update)
      return app

Under the general folder: Contents in the FlaskBluePrint/manager.py file:

from student import create_app

flask_app = create_app()


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

Under the general folder: Contents in the file FlaskBluePrint/student_data.py:

# Store student information
STUDENT = [
    {'id': 1, 'name': 'lisa', 'age': 38, 'gender': 'in'},
    {'id': 2, 'name': 'egon', 'age': 73, 'gender': 'male'},
    {'id': 3, 'name': 'annie', 'age': 84, 'gender': 'female'}
]

3.5 manage the web view of student information:

  

The above is the project structure directory of our Flask small application!!!

Posted by FD_F on Mon, 18 Nov 2019 23:51:34 -0800