1. 程式人生 > >Flask中的藍圖(BluePrint)、

Flask中的藍圖(BluePrint)、

 

藍圖

1.初識Flask藍圖(BluePrint)

建立一個專案然後將目錄結構做成:

user.py中的內容

from flask import Blueprint, render_template  # 匯入Flask中的藍圖BluePrint模組

# 例項化一個藍圖物件 users_blue = Blueprint('users', __name__, template_folder='user_temp', url_prefix='/user')

# 這裡新增路由和檢視函式的時候與在Flask物件中新增是一樣的
@users_blue.route('/user_add')  # /user/user_add
def user_add():
    return render_template('user_add.html')  # 會優先從外面找,如果外層有同名的html就展示的是外層的  

app_blue.py中的內容

from flask import Flask, render_template, request, session, redirect
import setting
from serv import users  # 匯入寫好的藍圖模組

app = Flask(__name__, template_folder='temp', static_folder='jingtaiwenjianmulu', static_url_path='/static')
app.config.from_object(setting.Debug)
# 在Flask物件中註冊藍圖模組中的藍圖物件 users中的user_blue app.register_blueprint(users.users_blue) @app.route('/detail', endpoint='detail') def detail(): return render_template('detail.html') @app.route('/login', methods=['GET', 'POST'], strict_slashes=False) def login(): if request.method == 'GET': return render_template('login.html') else: session['user'] = request.form.get('username') return redirect('/') if __name__ == '__main__': app.run(debug=True)  

巨坑:

  藍圖內部的檢視函式及route不要出現重複。

3.使用藍圖,做一個增刪改查使用者

要有一個檔案存放我們的原始資料

student_data.py檔案中的內容:

STUDENT = [
    {'id': 1, 'name': 'w', 'age': 22, 'gender': '中'},
    {'id': 2, 'name': 'j', 'age': 23, 'gender': '男'},
    {'id': 3, 'name': 's', 'age': 24, 'gender': '女'},
]

  然後我們根據以上內容進行增刪改查

3.1使用藍圖進行web應用搭建:

__init__.py檔案中的內容:

from flask import Flask


def create_app():
    app = Flask(__name__)
    
    return app

這個檔案我們會修改函式create_app中的程式碼

student_manager.py檔案中的內容:

from student import create_app


flask_app = create_app()

flask_app.run('0.0.0.0', 5000) 

通過這種方式啟動Flask程式

3.2 使用藍圖檢視學生資訊

stu_list.html檔案的內容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>學生列表</title>
</head>
<body>
<a href="/stu_add">新增學生</a>
<table border="3px">
    <thead>
    <tr>
        <th>ID</th>
        <th>name</th>
        <th>age</th>
        <th>gender</th>
        <th>options</th>
    </tr>
    </thead>
    <tbody>
    {% for stu in student %}
        <tr>
        <td>{{ stu.id }}</td>
        <td>{{ stu.name }}</td>
        <td>{{ stu.age }}</td>
        <td>{{ stu.gender }}</td>
        <td><a href="/stu_update/{{ stu.id }}">編輯</a> | <a href="/stu_delete?id={{ stu.id }}">刪除</a></td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>

stu_select.py檔案中的內容:

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

stu_blueprint = Blueprint('stu_bp', __name__, template_folder='html', static_folder='static')


@stu_blueprint.route('/stu_list')
def stu_list():
    return render_template('stu_list.html', student=STUDENT)

 student/__init__.py檔案中的內容:

from flask import Flask
from student_select import stu_select


def create_app():
    app = Flask(__name__)
    app.register_blueprint(stu_select.stu_blueprint)
    
    return app  

3.3使用Flask藍圖,新增一個學生

stu_add.html中內容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>新增學生</title>
</head>
<body>
<form action="" method="post">
    ID:    <input type="text" name="id"> <br>
    姓名: <input type="text" name="name"> <br>
    年齡: <input type="text" name="age"> <br>
    性別: <input type="text" name="gender"><br>
    <input type="submit" value="新增學生">
</form>
</body>
</html>  

stu_add.py中的內容

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

stu_add = Blueprint('stu_add', __name__, template_folder='html')


@stu_add.route('/stu_add', methods=['GET', 'POST'])
def stu_add_view():
    if request.method == 'POST':
        stu_dic = {
            'id': request.form['id'],
            'name': request.form['name'],
            'age': request.form['age'],
            'gender': request.form['gender'],
        }
        STUDENT.append(stu_dic)
        
        return redirect('/stu_list')
    return render_template('stu_add.html')

 student/__init__.py檔案中的內容

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


def create_app():
    app = Flask(__name__)
    app.register_blueprint(stu_select.stu_blueprint)
    app.register_blueprint(stu_add.stu_add)

    return app  

3.4使用Flask藍圖,修改學生資訊

stu_update.html檔案中的內容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>學生列表</title>
</head>
<body>
<form action="" method="post">
    <input type="text" name="id" hidden value="{{ student.id }}"><br>
    姓名:<input type="text" name="name" value="{{ student.name }}"><br>
    年齡:<input type="text" name="age" value="{{ student.age }}"><br>
    性別:<input type="text" name="gender" value="{{ student.gender }}"><br>
    <input type="submit" value="修改資訊">
</form>
</body>
</html>  

 stu_update.py中的內容

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

stu_update = Blueprint('stu_update', __name__, template_folder='html')


@stu_update.route('/stu_update/<nid>', methods=['GET', 'POST'])
def stu_update_view(nid):
    if request.method == 'POST':
        stu_id = 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('/stu_list')
    for stu in STUDENT:
        if stu['id'] == nid:
            return render_template('stu_update.html', student=stu)
    return render_template('stu_update.html', student='')  

 student/__init__.py檔案中的內容:

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__)
    app.register_blueprint(stu_select.stu_blueprint)
    app.register_blueprint(stu_add.stu_add)
    app.register_blueprint(stu_update.stu_update)

    return app

3.5使用Flask藍圖,刪除學生資訊