Flask 組件 Blueprint

Blueprint 簡介:

Blueprint 譯爲藍圖。簡單來說,Blueprint 是一個存儲操作方法的容器,這些操作在這個Blueprint 被註冊到一個應用之後就可以被調用,Flask 可以通過Blueprint來組織URL以及處理請求。

  1. Flask 使用 Blueprint 讓應用實現模塊化,在Flask中,Blueprint具有如下屬性:

  2. 一個應用可以具有多個Blueprint,可以將一個Blueprint註冊到任何一個未使用的URL下比如 “/”、“/sample”或者子域名

  3. 在一個應用中,一個模塊可以註冊多次

  4. Blueprint 可以單獨具有自己的模板、靜態文件或者其它的通用操作方法,它並不是必須要實現應用的視圖和函數的在一個應用初始化時,就應該要註冊需要使用的 Blueprint

  5. 但是一個 Blueprint 並不是一個完整的應用,它不能獨立於應用運行,而必須要註冊到某一個應用中

Blueprint 執行步驟:

  1. 創建一個藍圖對象

  2. 在這個藍圖對象上進行操作,註冊路由

  3. 在應用對象上註冊這個藍圖對象

Blueprint 使用:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from flask import Flask, Blueprint


# 創建 app
app = Flask(__name__)

# 創建藍圖
blueprint = Blueprint('app', __name__)


# 註冊路由
@blueprint.route('/')
# 視圖函數
def hello_world():
    return 'Hello World!'


# 註冊藍圖
app.register_blueprint(blueprint)

if __name__ == '__main__':
    app.run(debug=True)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章