Flask蓝图Blueprint和特殊装饰器

Flask 中的 蓝图 Blueprint

不能被run的flask实例;相当于django中的app01 应用

蓝图作用:功能隔离 路由隔离

Blueprint就是 一个不能run的flask

蓝图的名称app01user 必须保证在app中是唯一

url_prefix 是url前缀;用于隔离相同url

# blueprint.py
from flask import Flask
app = Flask(__name__)
app.debug = True

# 建立蓝图注册  一定要注册
from app01.views import user as app01_user
from app02.views import user as app02_user

app.register_blueprint(app01_user)
app.register_blueprint(app02_user)


if __name__ == '__main__':
    app.run()

app01

from flask import Blueprint, render_template

# Blueprint就是 一个不能run的flask

# 蓝图的名称app01user 必须保证在app中是唯一
user = Blueprint("app01user", __name__, template_folder="app01/templates/", url_prefix="/admin")  # url_prefix是url前缀;用于隔离相同url


@user.route('/login')
def login():
    # return "i am app01 blueprint"
    return render_template("login.html")

app02

from flask import Blueprint, render_template

# Blueprint就是 一个不能run的flask
user = Blueprint("app02user", __name__, url_prefix="/shopping")  # url_prefix


@user.route('/login')
def login():
    return "i am app02 blueprint"
# return render_template('login.html')

蓝图结构

  • 项目文件下分别创建manage.py 创建app01目录;
  • 在app01目录下分别创建views文件夹、static文件夹、templates文件夹、init.py、models.py
  • views 文件夹下创建蓝图 blueprint
    Flask蓝图Blueprint和特殊装饰器_第1张图片
# __init__,py
from flask import Flask
from app01.views.blueptrint import user #导入蓝图
def create_app():
    app = Flaks(__name__)
    app.congig['DEBUG'] = True
    
    # 注册蓝图
    app.register_blueprint(user)
    
    # 将app返回
    return app
# manage.py
# 导入app 实例
from app01 import create_app
app = create_app()

# 运行
if __name__ = '__main__'
    app.run()
# views 下 创建蓝图 blueprint
from flask import Blueprint
# 蓝图实例 user为蓝图名称
user = Blueprint("user" , __name__)

@user.route("/login")
def login():
    return "ok 200"

此时就可以运行manage.py文件了;或者Terminal下执行命令 python manage.py运行。

Flask 特殊装饰器

  • @app.before_request 请求进入视图函数之前

  • @app.after_request 请求结束,返回影响客户端之前

    正常 be1 - be2 - be3 - vf - af3 - af2 - af1
    异常 be1 - be2 - af3 - af2 - af1

  • @app.errorhandler(4xx or 5xx) 重定义错误信息

from flask import Flask, request, session, redirect, render_template
from functools import wraps

app = Flask(__name__)
app.secret_key = "!@#$%^&*()"
USER = {"username": "anwen"}


# def wrapper(func):
#   @wraps(func)
#   def inner(*args, **kwargs):
#       if session.get("user"):
#           ret = func(*args, **kwargs)
#           return ret
#       else:
#           return redirect("/login")
#
#   return inner


@app.before_request
def be1():
    print("be1")


@app.before_request
def be2():
    print("be2")
    if request.path == "/login":
        return None
    if session.get("user"):
        return None
    else:
        return redirect("/login")


@app.before_request
def be3():
    print("be3")


@app.after_request
def af1(res):
    print("af1")
    return res


@app.after_request
def af2(res):
    print("af2")
    return res


@app.after_request
def af3(res):
    print("af3")
    return res


@app.route('/login', methods=["GET", "POST"])
# @wrapper
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        if request.form.get("username") == USER["username"]:
            session['user'] = request.form.get("username")
            return redirect('/index')


@app.route("/index")
# @wrapper
def index():
    print("我是视图函数index")
    return render_template("index.html")


@app.route("/index1")
# @wrapper
def index1():
    return render_template("index.html")


@app.route("/index2")
# @wrapper
def index2():
    return render_template("index.html")


@app.errorhandler(404)
def error404(ErrorMessage):
    print(ErrorMessage)
    return redirect("https://www.autohome.com.cn/beijing/asdfe32r24rff23r23r")
    # return send_file("image/1.jpg")


if __name__ == '__main__':
    app.run()

你可能感兴趣的:(Flask蓝图Blueprint和特殊装饰器)