当前位置:网站首页>Beginner of flask framework-04-flask blueprint and code separation
Beginner of flask framework-04-flask blueprint and code separation
2022-07-26 10:02:00 【Flowing ink fragrance】
This article will be based on the knowledge points and blueprints of the previous chapter , Explain one with flask The simple login and registration business implemented by the framework .
The blueprint
When the business volume is increasing , In different businesses, it is easy to have more than add、insert、update、delete Such a word named route , This makes the routing name difficult to control . So in Flask The concept of blueprint is introduced into the framework , Every business belongs to a blueprint , Under every blueprint, there can be add、insert The route named like this , However, there cannot be the same route name under the same blueprint . The emergence of the blueprint concept greatly simplifies the entire application , Split application components , Make the application components as low as possible , It has the following features :
- Decompose an application into a collection of blueprints , There can be many routes under a blueprint , Different blueprints can have the same route ( It can be distinguished by blueprints )
- Use different ones in an application URL The rule registers a blueprint multiple times
- Provide template filters through blueprints 、 Static files 、 Templates and other features
- Initialize a Flask When expanding , In these cases, register a blueprint
Blueprint implementation steps :
1、 Declare creating a blueprint in the view
# Declare a route prefix as user, The name is user_bp The blueprint of The first parameter is zero :url_prefix
user_bp = Blueprint('user',__name__)
2、 stay app Registration blueprint
# stay Flask Core objects of app Middle statement template、static Storage address , That is, the path of the blueprint folder
app = Flask(' Folder path of different blueprints ',__name__,template_folder='../templates',static_folder='../static')
# Register associated blueprints
app.register_blueprint(user_bp)
# Print out app Under the url
print(app.url_map)
# View the contents of the resource folder
print(user.root_path)
Example
We all know web The three components of the project framework :MVC, namely model( Model )、view( View ) as well as controller( controller ). stay flask Of app Under the folder , Extract each different business code , Such as user business , Commodity business, etc , Under each business , Pulled out again model Store the data model ,controller Control business logic and jump view . And with the app The folder at the same level stores each jump view View interface .
The overall framework of the project ( here view.py For the control layer ):
First , We create a settings.py Store configuration information
# The configuration file
ENV = 'development'
DEBUG = True
stay app Under bag __init__.py Create a create_app Method , The main function of this method is to extract app.py The creation of flask Examples and some code associated between modules . Instantiation Flask You can specify templates and static The storage path of the folder , Blueprints increase with the increase of view control , Here is the blueprint associated with a user
from flask import Flask
import settings
from app.user.view import user_bp
def create_app():
# app It's a core object , Create... Here
app = Flask(__name__,template_folder='../templates',static_folder='../static')
# Load the configuration
app.config.from_object(settings)
# Blueprint Association
app.register_blueprint(user_bp)
print(app.url_map)
return app
To write app.py file , This file is a startup file , It is the key to start the whole program
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
Create a model.py, To write User class ,
class User:
def __init__(self,username,password,phone=None):
self.username = username
self.password = password
self.phone = phone
def __str__(self):
return self.username
To write view.py, There is a registered one named user The blueprint of , And registration 、 Sign in 、 sign out 、 modify 、 Delete 、 Presentation method
from flask import Flask, Blueprint, request, render_template
from werkzeug.utils import redirect
from app.user.model import User
user_bp = Blueprint('user',__name__)
users = []
@user_bp.route('/')
def user_center():
return render_template('user/show.html',users=users)
@user_bp.route('/register',methods=['GET','POST'])
def register():
if request.method == 'POST':
# get data
username = request.form.get('username')
password = request.form.get('password')
repassword = request.form.get('repassword')
phone = request.form.get('phone')
if password == repassword:
# The only user
for user in users:
if user.username == username:
return render_template('user/register.html',msg=' User name already exists !')
# establish user object
user = User(username,password,phone)
# Add to user list
users.append(user)
return redirect('/')
return render_template('user/register.html')
@user_bp.route('/login',methods=['GET','POST'])
def login():
return ' The user login '
@user_bp.route('/logout',methods=['GET','POST'])
def logout():
return ' User exits '
@user_bp.route('/del')
def del_user():
# Get the delivered username
username = request.args.get('username')
# according to username Find... In the list user object
for user in users:
if user.username == username:
# Delete user
users.remove(user)
return redirect('/')
else:
return ' Delete failed !'
@user_bp.route('/update',methods=['GET','POST'],endpoint='update')
def update_user():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
phone = request.form.get('phone')
for user in users:
if user.username == username:
return render_template('show.html',user=user)
else:
username = request.args.get('username')
for user in users:
if user.username == username:
return render_template('user/register.html',user=user)
return
Jump to the parent view base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %} User center {% endblock %}</title>
<style> </style>
{% block mycss %}
{% endblock %}
</head>
<body>
<div id="header">
<ul>
<li><a href=""> home page </a></li>
<li><a href=""> seckill </a></li>
<li><a href=""> The supermarket </a></li>
<li><a href=""> The book </a></li>
<li><a href=""> members </a></li>
</ul>
</div>
<div id="middle">
{% block middle %}
{% endblock %}
</div>
<div id="footer"></div>
{% block myjs %}
{% endblock %}
</body>
</html>
Jump to view register.html
{% extends 'base.html' %}
{% block title %}
User registration
{% endblock %}
{% block middle %}
<p style="color: red">{
{ msg }}</p>
<form action="{
{url_for('user.register')}}" method="post">
<p><input type="text" name="username" placeholder=" user name "></p>
<p><input type="password" name="password" placeholder=" password "></p>
<p><input type="password" name="repassword" placeholder=" Confirm the password "></p>
<p><input type="number" name="phone" placeholder=" Phone number "></p>
<p><input type="submit" value=" User registration "></p>
</form>
{% endblock %}
Jump to view login.html Untreated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
Jump to view show.html
{% extends 'base.html' %}
{% block middle %}
<h1> User information </h1>
<span> The current number of users is :{
{ users | length }} people </span>
<table border="1" cellspacing="0" width="60%">
{% for user in users %}
<tr>
<td>{
{ loop.index }}</td>
<td>{
{ user.username }}</td>
<td>{
{ user.password }}</td>
<td>{
{ user.phone }}</td>
<td><a href="javascript:;" onclick="update('{
{ user.username }}')"> modify </a><a href="javascript:;" onclick="del('{
{ user.username }}')"> Delete </a> </td>
</tr>
{% endfor %}
</table>
{% endblock %}
{% block myjs %}
<script> // Delete user function del(username){
// console.log(username) location.href = '/del?username'+username' } // Modify user information function update(username){
alert(username) console.log(username) location.href = '/update?username'+username' } </script>
{% endblock %}
Jump to view update.html
{% extends 'base.html' %}
{% block title %}
User information modification
{% endblock %}
{% block middle %}
<h1> User information update </h1>
<form action="{
{ url_for('user.update') }}" method="post">
<p><input type="hidden" name="realname" value="{
{ user.username }}"></p>
<p><input type="text" name="username" placeholder=" user name " value="{
{ user.username }}"></p>
<p><input type="text" name="password" placeholder=" password " value="{
{ user.password }}" disabled></p>
<p><input type="text" name="pone" placeholder=" Phone number " value="{
{ user.phone }}"></p>
<p><input type="submit" value=""></p>
</form>
{% endblock %}
{% block %}
{% endblock %}
result :



边栏推荐
- Sqoop【付诸实践 02】Sqoop1最新版 全库导入 + 数据过滤 + 字段类型支持 说明及举例代码(query参数及字段类型强制转换)
- Why does new public chain Aptos meet market expectations?
- The use of MySQL in nodejs
- Double authentication of server and client
- Transform between tree and array in JS (hide the children field if the child node of the tree is empty)
- Opencv image processing
- Basic usage of protobuf
- 云原生(三十六) | Kubernetes篇之Harbor入门和安装
- R language ggpubr package ggsummarystats function visualizes the grouping box diagram (custom grouping color) and adds the statistical values corresponding to the grouping under the x-axis label (samp
- 2021年山东省中职组“网络空间安全”B模块windows渗透(解析)
猜你喜欢

Solve NPM -v sudden failure and no response
![Sqoop [environment setup 01] CentOS Linux release 7.5 installation configuration sqoop-1.4.7 resolve warnings and verify (attach sqoop 1 + sqoop 2 Latest installation package +mysql driver package res](/img/8e/265af6b20f79b21c3eadcd70cfbdf7.png)
Sqoop [environment setup 01] CentOS Linux release 7.5 installation configuration sqoop-1.4.7 resolve warnings and verify (attach sqoop 1 + sqoop 2 Latest installation package +mysql driver package res

Xiaobai makes a wave of deep copy and shallow copy

El table implements adding / deleting rows, and a parameter changes accordingly

数通基础-TCPIP参考模型

Applet record

PMM (percona monitoring and management) installation record

Transform between tree and array in JS (hide the children field if the child node of the tree is empty)

2022年中科磐云——服务器内部信息获取 解析flag

数通基础-网络基础知识
随机推荐
数通基础-二层交换原理
Mysql5.7.25 master-slave replication (one-way)
Study notes of the second week of sophomore year
copyTo
时间序列异常检测
Customize permission validation in blazor
Flask框架初学-04-flask蓝图及代码抽离
Leetcode 504. 七进制数
Applet record
面试突击68:为什么 TCP 需要 3 次握手?
The diagram of user login verification process is well written!
R language ggplot2 visualization: align the legend title to the middle of the legend box in ggplot2 (default left alignment, align legend title to middle of legend)
新公链Aptos何以拉满市场期待值?
2021 windows penetration of "Cyberspace Security" B module of Shandong secondary vocational group (analysis)
Principle analysis and source code interpretation of service discovery
反射机制的原理是什么?
服务器内存故障预测居然可以这样做!
Usage of the formatter attribute of El table
Uni app learning summary
新增市场竞争激烈,中国移动被迫推出限制性超低价5G套餐