自学内容网 自学内容网

3.flask蓝图使用

构建一个目录结构

user_oper.py

from flask import Blueprint, request, session, redirect, render_template
import functools
# 创建蓝图
user = Blueprint('xkj', __name__)

DATA_DICT = {
    1: {"name": "张三", "age": 22, "gender": "男"},
    2: {"name": "小红", "age": 18, "gender": "女"}
}


@user.route("/f1")
def f1():
    return 'xkj1'


# 使用装饰器来统一验证用户是否登录
def outer(func):
    # 保证被装饰器装饰的函数的__name__值为原函数名称
    @functools.wraps(func)
    def inner(*args, **kwargs):
        # 验证用户是否登录
        if not session.get('xx'):
            return redirect("/web/login")
        # 这里的return一定不能少,否则
        # TypeError: The view function for 'index' did not return a valid response.
        return func(*args, **kwargs)
    return inner


@user.route("/login", methods=["GET", "POST"])
def login():
    error = None
    method = request.method
    if method == "POST":
        username = request.form.get('username')
        password = request.form.get('password')
        if username == 'admin' and password == '123':
            # 将用户信息存入session中
            session['xx'] = username
            return redirect("/web/index")
        else:
            error = "用户名或密码错误"

    return render_template("login.html", error=error)


@user.route("/index")
@outer
def index():
    return render_template("index.html", DATA_DICT=DATA_DICT)


@user.route("/edit", methods=['POST', 'GET'])
@outer
def edit():
    method = request.method
    nid = int(request.args.get("nid"))
    if method == 'POST':
        DATA_DICT[nid]['name'] = request.form.get('name')
        DATA_DICT[nid]['age'] = request.form.get('age')
        DATA_DICT[nid]['gender'] = request.form.get('gender')
        return redirect("/web/index")
    user_data = DATA_DICT.get(nid)
    return render_template("edit.html", info=user_data)


# <int:nid>中间一定不能有空格
@user.route("/del/<int:nid>")
@outer
def delete(nid):
    del DATA_DICT[nid]
    return redirect("/web/index")

middle_aware.py 

from flask import Flask
from demo.user_oper import user


def create_app():
    app = Flask(__name__)
    # 使用session,就必须设置app.secret_key的值
    app.secret_key = "1"
    app.register_blueprint(user, url_prefix="/web")
    return app

start.py

from middle_aware import create_app

app = create_app()

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080)


原文地址:https://blog.csdn.net/qq_36352889/article/details/145083500

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!