温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Flask blueprint

发布时间:2020-06-16 22:52:23 来源:网络 阅读:3742 作者:Ohimma 栏目:开发技术

一、简介

面向对象的基本思想:多聚合、少继承、低(松)耦合、高内聚

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI