flask 蓝本 例子(flask 42)

2019-08-13 14:49:15 浏览数 (1)

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')


from flask import Blueprint

admin=Blueprint('admin',name) @admin.route('/xx')

from .admin import admin app.register_blueprint(admin,url_prefix='/admin')

0 人点赞