Flask框架第六篇.Flask中的蓝图和特殊装饰器

1.Flask中的蓝图 Blueprint (app01)

不能被run的Flask实例,不存在config

Flask蓝图 https://www.cnblogs.com/DragonFire/p/9264381.html

app01.py

from flask import Blueprint
​
bp = Blueprint("app01",__name__)  
​
@bp.route("/add_user")
def add_user():
    return "添加用户"
​
@bp.route("/del_user")
def del_user():
    return "删除用户"
​
@bp.route("/update_user")
def update_user():
    return "修改用户"
​
@bp.route("/find_user")
def find_user():
    return "查找用户"
View Code

app02.py

from flask import Blueprint
​
car_bp = Blueprint("app02",__name__,url_prefix="/car")  # url_prefix  url前缀
​
@car_bp.route("/add_user")
def add_user():
    return "car添加用户"
​
@car_bp.route("/del_user")
def del_user():
    return "car删除用户"
​
@car_bp.route("/update_user")
def update_user():
    return "car修改用户"
​
@car_bp.route("/find_user")
def find_user():
    return "car查找用户"
View Code

测试

from flask import Flask
from app01 import bp
from app02 import car_bp
​
app = Flask(__name__)
app.register_blueprint(bp)  #注册蓝图
app.register_blueprint(car_bp)
​
if __name__ == '__main__':
    app.run("0.0.0.0",9527)
View Code

2.特殊装饰器

Flask特殊装饰器 https://www.cnblogs.com/DragonFire/p/9269303.html

@app.before_request   #在请求进入视图函数之前,做出处理
​
@app.after_request    #在响应返回客户端之前,结束视图函数之后
# be + af请求生命周期
     正常 : be1 --> be2 --> vf -->af2 --> af1
     异常 : be1 -->af2 --> af1
     # 总结:只要有响应返回,af全都执行 
    
@app.errorhandler(404)    #重定义错误返回信息 HttpErrorCode()  
from flask import Flask,session,jsonify
from setting import DebugConfig,TestConfig
from users import bp
from car_user import car_bp
​
app = Flask(__name__,template_folder="templatess")
​
app.config.from_object(DebugConfig)
# app.config.from_object(TestConfig)
​
app.register_blueprint(bp)
app.register_blueprint(car_bp)
​
​
@app.before_request
def be1():
    print("be1")
​
@app.before_request
def be2():
    print("be2")
​
@app.after_request
def af1(res):
    print("af1")
    return res
​
@app.after_request
def af1(res):
    print("af2")
    return res
​
@app.errorhandler(404)
def error404(error_message):
    print(error_message)
    return "你的页面出错了"  #5种类型
if __name__ == '__main__':
    app.run()
View Code
from flask import Blueprint
​
bp = Blueprint("app01",__name__,)
​
@bp.route("/add_user")
def add_user():
    print("vf")
    return "添加用户"
View Code
posted @ 2021-11-17 19:30  Primrose  阅读(57)  评论(0编辑  收藏  举报