当前位置:网站首页>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 :



边栏推荐
猜你喜欢

Basic usage of protobuf

The diagram of user login verification process is well written!

SSG framework Gatsby accesses the database and displays it on the page

点赞,《新程序员》电子书限时免费领啦!

Principle analysis and source code interpretation of service discovery

MQTT X CLI 正式发布:强大易用的 MQTT 5.0 命令行工具

Uniapp "no mobile phone or simulator detected, please try again later" and uniapp custom components and communication

服务发现原理分析与源码解读

30分钟彻底弄懂 synchronized 锁升级过程

AR model in MATLAB for short-term traffic flow prediction
随机推荐
The problem of accessing certsrv after configuring ADCs
Spolicy request case
QT handy notes (VI) -- update interface, screenshot, file dialog box
(2) Hand eye calibration of face scanner and manipulator (eye out of hand: nine point calibration)
Apple dominates, Samsung revives, and domestic mobile phones fail in the high-end market
QT handy notes (III) use qtcharts to draw a line chart in VS
服务发现原理分析与源码解读
Leetcode 504. 七进制数
Installation and use of cocoapods
Flask框架初学-03-模板
Rowselection emptying in a-table
论文笔记(SESSION-BASED RECOMMENDATIONS WITHRECURRENT NEURAL NETWORKS)
Draw arrows with openlayer
Server memory failure prediction can actually do this!
Keeping alive to realize MySQL automatic failover
What is the principle of reflection mechanism?
Flask框架初学-04-flask蓝图及代码抽离
面试突击68:为什么 TCP 需要 3 次握手?
Interview shock 68: why does TCP need three handshakes?
Solve the problem of storing cookies in IE7 & IE8