当前位置:网站首页>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 :
边栏推荐
- Usage of the formatter attribute of El table
- Why does new public chain Aptos meet market expectations?
- Uniapp "no mobile phone or simulator detected, please try again later" and uniapp custom components and communication
- Sqoop【环境搭建 01】CentOS Linux release 7.5 安装配置 sqoop-1.4.7 解决警告并验证(附Sqoop1+Sqoop2最新版安装包+MySQL驱动包资源)
- 时间序列异常检测
- protobuf的基本用法
- Leetcode 504. Hex number
- Principle analysis and source code interpretation of service discovery
- JS table auto cycle scrolling, mouse move in pause
- JS judge the data types object.prototype.tostring.call and typeof
猜你喜欢
Due to fierce competition in the new market, China Mobile was forced to launch a restrictive ultra-low price 5g package
SQL优化的魅力!从 30248s 到 0.001s
I finished watching this video on my knees at station B
Principle analysis and source code interpretation of service discovery
MySQL 5.7.25 source code installation record
MQTT X CLI 正式发布:强大易用的 MQTT 5.0 命令行工具
数通基础-TCPIP参考模型
万字详解“用知识图谱驱动企业业绩增长”
分布式网络通信框架:本地服务怎么发布成RPC服务
开发转测试:从0开始的6年自动化之路...
随机推荐
I finished watching this video on my knees at station B
Azkaban【基础知识 01】核心概念+特点+Web界面+架构+Job类型(一篇即可入门Azkaban工作流调度系统)
Solve NPM -v sudden failure and no response
Leetcode 504. Hex number
Wechat H5 payment on WAP, for non wechat browsers
30分钟彻底弄懂 synchronized 锁升级过程
MySQL 5.7.25 source code installation record
Basic usage of protobuf
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)
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
挡不住了,纯国产PC已就位,美国的软硬件体系垄断正式被破
SQL优化的魅力!从 30248s 到 0.001s
R语言ggplot2可视化: 将图例标题(legend title)对齐到ggplot2中图例框的中间(默认左对齐、align legend title to middle of legend)
Alibaba cloud technology expert haochendong: cloud observability - problem discovery and positioning practice
PMM (percona monitoring and management) installation record
QT handy notes (III) use qtcharts to draw a line chart in VS
在Blazor 中自定义权限验证
In the same CONDA environment, install pytroch first and then tensorflow
Spolicy request case
2021年山东省中职组“网络空间安全”B模块windows渗透(解析)