Flask blueprint

一、簡介

面向對象的基本思想:多聚合、少繼承、低(鬆)耦合、高內聚

1、django的鬆耦合:體現在url和視圖函數之間,兩個之間的更改不需要依賴於對方內部構造

2、flask的blueprint:(藍圖/藍本)定義了可應用於單個應用的視圖,模板,靜態文件的集合,將應用組織成了不同的組件;我理解上就是模塊化,獨立。

比喻舉例

情景一:兩個人去吃麻辣香鍋,點一鍋上來,簡單方便吃的津津有味   
【兩個人開發的一個系統,放在一個文件內,傳送拷貝方便,也很好理解溝通】    
情景二:有一天同學聚餐,六十多人,點好幾大鍋,裏邊什麼都有,那就尷尬了,有的人不吃辣,有的人不吃這不吃那,一個菜一個碗區分開大家好弄   
【六十個人開發系統,同時從100行編輯文件,提交上去合併時就0疼了,各部分獨立出來,各自修改自己的部分,就顯得很和平了】

二、小案例

1:原始視圖:

# views.py

#!/usr/local/bin/python3
# -*- encoding: utf-8 -*-

from app import app

@app.route('/user/index')
def index():
    return 'user_index'

@app.route('/user/show')
def show():
    return 'user_show'

@app.route('/user/add')
def add():
    return 'user_add'

@app.route('/admin/index')
def adminindex():
    return 'admin_index'

@app.route('/admin/show')
def adminshow():
    return 'admin_show'

@app.route('/admin/add')
def adminadd():
    return 'admin_add'

#上面6個視圖,分別對應admin,user兩個用戶的三個功能,index、add、show

#如果admin、user不止三個功能,幾百個,幾千個,那僅view的代碼就不可review和維護了
#如果多個人同時開發admin,同時寫代碼提交,版本控制就會城災難
#如果我們要棄用admin功能塊,那我們要刪除多少行

2、使用藍圖使之pythonic

# admin.py

from flask import Blueprint,render_template, request

admin = Blueprint('admin', __name__)

@admin.route('/index')
def index():
    return render_template('admin/index.html')

@admin.route('/add')
def add():
    return 'admin_add'

@admin.route('/show')
def show():
    return 'admin_show'
# user.py

from flask import Blueprint, render_template, redirect

user = Blueprint('user',__name__)

@user.route('/index')
def index():
    return render_template('user/index.html')

@user.route('/add')
def add():
    return 'user_add'

@user.route('/show')
def show():
    return 'user_show'
# views.py

from app import app
from .user import user
from .admin import admin

#註冊藍圖並且設置request url條件
app.register_blueprint(admin,url_prefix='/admin')
app.register_blueprint(user, url_prefix='/user')

#現在再來回答上面三個問題就好回答了吧

三、設計架構

個人:大型應用先用 分區式,每個分區式內用功能式

功能式架構

yourapp/
    __init__.py
    static/
    templates/
        home/
        control_panel/
        admin/
    views/
        __init__.py
        home.py
        control_panel.py
        admin.py
    models.py

分區式架構

官方是這麼說的:像常規的應用一樣,藍圖被設想爲包含在一個文件夾中。當多個藍圖源於同一個文件夾時,可以不必考慮上述情況,但也這通常不是推薦的做法。

yourapp/
__init__.py
admin/
__init__.py
views.py
static/
templates/
home/
__init__.py
views.py
static/
templates/
control_panel/
__init__.py
views.py
static/
templates/
models.py

參考:https://spacewander.github.io/explore-flask-zh/7-blueprints.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章