flask蓝图

1.概念

  蓝图可以使我们的程序更加模块化,不同功能的路由可以放在不同的模块下,最后集中到启动类中

  它的作用就是将功能和主服务分开,类似django中我们创建的每一个app

 2.蓝图常见架构方式

2.1 功能式架构    

  按照每部分的功能来组织应用,模板放在同一文件夹,视图存放同一文件夹

yourapp/
    __init__.py
    static/
    templates/
        home/
        control_panel/
        admin/
    views/
        __init__.py
        home.py
        control_panel.py
        admin.py
    models.py

 视图文件中的除了__init__.py,每一个文件都是一个了蓝图

所有的蓝图通过顶级的__init__.py注册到Flask()

2.2 分区式架构

  按照每一部分所属的蓝图来组织应用,管理面板的所有的模板,视图和静态文件放在一个文件夹中,用户控制面板的则放在另一个文件夹中

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

参考来源出处:参考出处链接

2.3 蓝图标准目录结构及用法

__init__.py

from flask import Flask
from lastday.views.account import account
from lastday.views.user import user


def create_app():
    """
    创建app应用
    :return:
    """
    app = Flask(__name__)

    # 引入配置文件并应用
    app.config.from_object("settings.Development")

    app.register_blueprint(account)
    app.register_blueprint(user)

    # @app.before_request
    # def b1():
    #     print('b1')
    #
    #   b1 = app.before_request(b1)
    app.before_request(b1)  # app请求之前的中间件

    return app


def b1():
    print('app_b1')

views/account.py

from flask import Blueprint

account = Blueprint('account',__name__)

@account.before_request
def bb():
    print('account.bb')


@account.route('/login')
def login():
    return '登陆'

views/user.py

from flask import Blueprint,render_template

user = Blueprint('user',__name__)

@user.route('/user_list')
def user_list():
    return render_template('user_list.html')

templates/user_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <h1>用户列表</h1>
    ...
    <img src="/static/imgs/teacher.jpg">
</body>
</html>
View Code

manage.py

from lastday import create_app

app = create_app()


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

setting.py

class Base(object):
    SECRET_KEY = "fasdfasdf"

class Product(Base):
    pass

class Testing(Base):
    DEBUG = False

class Development(Base):
    DEBUG = True

输入http://127.0.0.1:5000/login,终端打印:

输入http://127.0.0.1:5000/user_list,终端打印:

3. web应用搭建

实现基本的增删改查

目录结构

data.py

STUDENT = [
    {"id":1,"name":"小a","age":"18"},
    {"id":2,"name":"小b","age":"38"},
    {"id":3,"name":"小c","age":"66"},
]

 manage.py

from student import create_app

app = create_app()

if __name__ == "__main__":
    app.run(port=5051,debug=True)

__init__.py 

from flask import Flask
from views import select
from views import add
from views import update
from views import dels

def create_app():
    app = Flask(__name__)
    app.register_blueprint(select.my_list)
    app.register_blueprint(add.my_add)
    app.register_blueprint(update.my_update)
    app.register_blueprint(dels.my_del)

    return app

selsect.py

from flask import Blueprint
from flask import render_template
from data import STUDENT

my_list = Blueprint("my",__name__,template_folder="../templates")


@my_list.route("/list")
def lists():
    return render_template("list.html", student=STUDENT)

list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table border="2px">
    <button><a href="/add">添加</a></button>
    <thead>
        <tr>
            <th>id</th>
            <th>name</th>
            <th>age</th>
            <th>options</th>
        </tr>
    </thead>
    <tbody>
    {% for foo in student %}
         <tr>
            <td>{{ foo.id }}</td>
            <td>{{ foo["name"] }}</td>
            <td>{{ foo["age"] }}</td>
            <td><a href="/update/{{ foo.id }}">修改</a>|<a href="/del/{{ foo.id }}">删除</a></td>
        </tr>
    {% endfor %}
    </tbody>
</table>

</body>
</html>
View Code

add.py

from flask import Blueprint
from flask import request
from flask import render_template
from data import STUDENT

my_add = Blueprint("add",__name__,template_folder="../templates")

@my_add.route("/add",methods=["GET","POST"])
def adds():
    if request.method == "POST":
        add_dic = {
            "id": request.form["id"],
            "name": request.form["name"],
            "age": request.form["age"],
        }
        STUDENT.append(add_dic)
        return render_template("add.html")

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post">
    id:<input type="text" name="id"> <br>
    姓名:<input type="text" name="name"><br>
    年龄:<input type="text" name="age"><br>
    <input type="submit" value="添加">
</form>
</body>
</html>
View Code

update.py

#!/usr/bin/env python    # -*- coding:utf-8 -*-
# author: Learning       time:2018/9/7

from flask import Blueprint
from flask import request,redirect
from flask import render_template
from data import STUDENT

my_update = Blueprint("my_update",__name__,template_folder="../templates")

@my_update.route("/update/<int:nid>",methods=["GET","POST"])
def updates(nid):
    if request.method == "POST":
        ids = int(request.form["id"])
        add_dic = {
            "id": ids,
            "name": request.form["name"],
            "age": request.form["age"],
        }
        for index,dicts in enumerate(STUDENT):
            if dicts["id"] == ids:
                STUDENT[index] = add_dic

        return redirect("/list")

    # 首次访问,get请求

    for dic in STUDENT:
        if dic["id"] == nid:
            return render_template("update.html", student=dic)

    return render_template("update.html", student=" ")

update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post">
    <input type="text" name="id" hidden value="{{ student.id }}"><br>
    姓名:<input type="text" name="name" value="{{ student.name }}"><br>
    年龄:<input type="text" name="age" value="{{ student.age }}"><br>
    <input type="submit" value="修改信息">
</form>
</body>
</html>
View Code

dels.py

from flask import Blueprint
from flask import redirect
from data import STUDENT

my_del = Blueprint("my_del",__name__,template_folder="../templates")

@my_del.route("/del/<int:nid>",methods=["GET","POST"])
def dels(nid):
    for dic in STUDENT:
        if dic["id"] == nid:
            STUDENT.remove(dic)

    return redirect("/list")

效果:

 4.总结

1.Flask路由
    1.endpoint="user" # 反向url地址
    2.url_address = url_for("user")
    3.methods = ["GET","POST"] # 允许请求进入视图函数的方式
    4.redirect_to # 在进入视图函数之前重定向
    5./index/<nid> # 动态参数路由 <int:nid> def index(nid)
    6.strict_slashes # 是否严格要求路由地址 /
    7.defaults={"nid":1} # def index(nid)

2.Flask初始化配置(实例化):
    1.template_folder # 指定模板路径
    2.static_url_path # 指定静态文件目录的URL地址
    3.static_folder # 指定静态文件目录路径

3.Flask对象配置
    1.DEBUG #开发模式的调试功能 True False
    2.app.config.from_object(class) # 通过对象的方式导入配置
    3.secret_key # 开启session功能的时候需要添加的配置

4.Blueprint
    1.将功能和主程序分离,注册
    2.bl = Blueprint("dongdong",__name__)
    3.注册 register_blueprint(bl)
    
5.send_file jsonify
    1.send_file # 打开并返回文件 content-type:文件类型
    2.jsonify # 将一个字符串 转为JSON格式 加入 content-type:application/json 头
    
6.特殊的装饰器:
    1.before_request # 在请求进入视图函数之前执行的函数(登录认证)
    2.after_request # 在请求响应回浏览器之前执行的函数
    3.before_first_request # 在第一次请求进入视图函数之前执行的函数
    4.errorheader(404) # 当遇到此类错误响应的时候(自定义错误页面)

7.flash
    1.flash("msg","tag") # 闪现存储
    2.get_flashed_messages(category_filter=["tag"]) # 闪现取值
    只要用到了get_flashed_messages就一定清空flash

 

详细介绍可参考链接:https://www.cnblogs.com/wupeiqi/articles/7552008.html

转载于:https://www.cnblogs.com/LearningOnline/p/9601911.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值