Flask Blueprint

2020-01-15 17:06:39 浏览数 (1)

Blueprint简介

Blueprint它是Flask项目的一种组件式开发,可以在一个应用内或跨越 多个项目共用蓝图。使用蓝图可以极大地简化大型应用的开发难度,也为Flask扩展 提供了一种在应用中注册服务的集中式机制。 模块化管理程序路由是它的特色,它使程序结构清晰、简单易懂。但是一个Blueprint并不是一个完整的应用,它不能独立于应用运行,而必须要注册到某一个应用中。

由于只是演示蓝图的基本用法,所以这里以展示用户表,登陆认证,编辑用户,删除用户,新增用户来模拟多个模块作为演示。

环境搭建:

1、创建项目damo_2,在该项目下创建static(存放图片,css样式,js脚本等)、templates(HTML文件)两个目录。

2、新建一个settings.py的配置文件,配置文件中存放用户表

代码语言:javascript复制
USER_INFO = [{'aaa':'111'},{'bbb':'222'},{'ccc':'333'}]  # 模拟数据库中的用户表

一、函数的方式(FBV):

1、展示用户表

1.1创建show.py

代码语言:javascript复制
from flask import Blueprint,render_template
from settings import USER_INFO

show_app = Blueprint('show_app',__name__)
@show_app.route('/show_page')
def show_page():
    return render_template('show_page.html',user_info=USER_INFO)

 1.2在templates目录下创建show_page.html

代码语言:javascript复制
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3 style="margin-left: 320px">用户详情表</h3>
<form action="">
    <table border="1px">
        <thead>
        <tr>
            <th style="width: 150px;">序号</th>
            <th style="width: 150px;">用户</th>
            <th style="width: 150px;">密码</th>
            <th style="width: 150px;">操作</th>
        </tr>
        </thead>
        <tbody>
        {% for user_dict in user_info %}

            <tr>
                <td style="text-align: center">{{ loop.index0 }}</td>
                {% for user in user_dict %}
                    <td style="text-align: center">{{ user }}</td>
                    <td style="text-align: center">{{ user_dict.get(user) }}</td>
                {% endfor %}
                <td style="text-align: center">
                    <a href="/edit_user?id={{ loop.index0 }}">编辑</a>
                    |
                    <a href="/del_user?id={{ loop.index0 }}">删除</a>
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
    <br>
    <a href="/add_user">新增</a>
</form>
</body>
</html>

show_page

2、新增用户

2.1创建add_user.py

代码语言:javascript复制
from flask import Blueprint, request, render_template, redirect
from settings import USER_INFO

add_user_app = Blueprint('add_user', '__name__')

@add_user_app.route('/add_user', methods=['GET', 'POST'])
def add_user():
    if request.method == 'POST':
        user = request.form.get('username')
        pwd = request.form.get('password')
        USER_INFO.append({user: pwd})
        return redirect('/show_page')
    else:
        return render_template('add_user.html')

 2.2在templates目录下创建add_user.html

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    <h3>新增用户界面</h3>
    用户名:<input type="text" name="username">
    密码:<input type="password" name="password">
    <button>新增</button>
</form>
</body>
</html>

add_user

3、编辑用户

3.1创建edit_user.py文件 

代码语言:javascript复制
from flask import Blueprint, render_template, request, redirect
from settings import USER_INFO

edit_user_app = Blueprint('edit_user', '__name__')

@edit_user_app.route('/edit_user', methods=['GET', 'POST'])
def edit_user():
    uid = int(request.args.get('id'))
    if request.method == 'POST':
        user = request.form.get('username')
        pwd = request.form.get('password')
        nlen = len(USER_INFO)
        if 0 > uid or uid >= nlen:
            return f'索引不存在,索引范围是:0-{nlen - 1}'
        else:
            USER_INFO[uid] = {user: pwd}
        return redirect('/show_page')
    else:
        user_info = USER_INFO[uid]
        return render_template('edit_user.html', user_info=user_info)

  3.2在templates目录下创建edit_user.html

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
<h3>编辑用户界面</h3>
    {% for user in user_info %}
    用户名:<input type="text" name="username" value="{{ user }}">
    密码:<input type="password" name="password" value="{{ user_info[user] }}">
    {% endfor %}


    <button>保存</button>
</form>
</body>
</html>

edit_user

4、删除用户

4.1创建del_user.py

代码语言:javascript复制
from flask import Blueprint,request,render_template,redirect
from settings import USER_INFO

del_user_app = Blueprint('del_user','__name__')

@del_user_app.route('/del_user')
def del_user():
    uid = int(request.args.get('id'))
    USER_INFO.pop(uid)
    return redirect('/show_page')

5、创建damo_2.py主文件

代码语言:javascript复制
from flask import Flask, session, request, redirect, render_template
from flask import session
from show import show_app
from index import index_app
from add_user import add_user_app
from del_user import del_user_app
from edit_user import edit_user_app
from login import login_app

user_app = Flask('__name__')
user_app.secret_key = '~!@#$%^&*'
user_app.config['DEBUG'] = True

@user_app.before_request
def session_check():  # 中间件用户登陆认证,用户必须登录后才能访问展示页面
    if session.get('user') or request.path == '/login':
        return None
    else:
        return redirect('/login')
@user_app.after_request
def response_after(response):
    return response
user_app.register_blueprint(index_app)     # 注册公共展示页面
user_app.register_blueprint(show_app)      # 注册用户详情页面
user_app.register_blueprint(add_user_app)  # 注册新增用户页面
user_app.register_blueprint(del_user_app)  # 注册删除用户页面
user_app.register_blueprint(edit_user_app) # 注册编辑用户页面
user_app.register_blueprint(login_app)     # 注册用户登陆页面
@user_app.errorhandler(404)                # 404错误页面
def error404(error_msg):
    return render_template('error404.html')

user_app.run()

 二、使用类的方式(CBV)

1、修改展示页面show.py

代码语言:javascript复制
from flask import Blueprint, render_template
from settings import USER_INFO
from flask import views

show_app = Blueprint('show_app',__name__)

class ShowPage(views.MethodView):
    def get(self):
        return render_template('show_page.html', user_info=USER_INFO)

show_app.add_url_rule('/show_page', view_func=ShowPage.as_view(name='show_page'))

2、修改新增用户add_user.py

代码语言:javascript复制
from flask import Blueprint, request, render_template, redirect
from settings import USER_INFO
from flask import views

add_user_app = Blueprint('add_user', '__name__')

class AddUser(views.MethodView):
    def get(self):
        return render_template('add_user.html')

    def post(self):
        user = request.form.get('username')
        pwd = request.form.get('password')
        USER_INFO.append({user: pwd})
        return redirect('/show_page')
add_user_app.add_url_rule('/add_user',view_func=AddUser.as_view(name='add_user'))

3、修改编辑用户edit_user.py

代码语言:javascript复制
from flask import Blueprint, render_template, request, redirect
from settings import USER_INFO
from flask import views

edit_user_app = Blueprint('edit_user', '__name__')

class EditUser(views.MethodView):
    def get(self):
        uid = int(request.args.get('id'))
        user_info = USER_INFO[uid]
        return render_template('edit_user.html', user_info=user_info)

    def post(self):
        uid = int(request.args.get('id'))
        user = request.form.get('username')
        pwd = request.form.get('password')
        nlen = len(USER_INFO)
        if 0 > uid or uid >= nlen:
            return f'索引不存在,索引范围是:0-{nlen - 1}'
        else:
            USER_INFO[uid] = {user: pwd}
        return redirect('/show_page')
edit_user_app.add_url_rule('/edit_user',view_func=EditUser.as_view(name='edit_view'))

 4、修改删除用户del_user.py

代码语言:javascript复制
from flask import Blueprint,request,render_template,redirect
from settings import USER_INFO
from flask import views
del_user_app = Blueprint('del_user','__name__')

class DelUser(views.MethodView):
    def get(self):
        uid = int(request.args.get('id'))
        USER_INFO.pop(uid)
        return redirect('/show_page')
del_user_app.add_url_rule('/del_user',view_func=DelUser.as_view(name='del_user'))

 页面展示如下:

0 人点赞