当前位置:网站首页>Flask framework - Message flash
Flask framework - Message flash
2022-07-25 10:53:00 【White chocolate Lin】
Catalog
In the last article, we learned Flask frame ——flask-caching cache , Let's study this article Flask frame ——flash The news flashed .
good web The application needs to provide feedback to users , for example : When the user enters information and clicks submit , The web page will prompt whether the submission is successful or the submitted information is incorrect .
Flask The framework provides a simple way of feedback through the flash system . Its basic working principle is : Record a message at the end of the current request , Provide to the current request or the next request . for example : The user is in A Jump to B page , stay B The page shows A Page error messages . At this time, the error message can be passed to B page .
Use message flash
Flask The framework provides flash() Method to realize message flash , In the view function, use flash() Method to pass the message to the next request , This request is usually a template .
flash() The syntax structure of the method is :
flash(message,category)
among :
message: Mandatory , Data and information ;
category: Optional , Flash type .
Be careful : When using message flash , Need configuration SECRET_KEY Value , The value can be any character .
The sample code is as follows :
from flask import Flask, render_template, request, flash
app = Flask(__name__)
app.config['SECRET_KEY']='sfasf' # To configure SECRET_KEY, The value is any character
@app.route('/',methods=['GET','POST'])
def flash_message():
if request.method=='POST':
username=request.form.get('username') # Get submitted username value
if username=='admin': # Verify that it is admin
flash(' Verify success ') # Use flash Method to pass information
return render_template('index.html') # Use render_template() Method render template index.html
else:
flash(' Validation failed ') # Use flash Method to pass information
return render_template('index.html') # Use render_template() Method render template index.html
return render_template('login.html') # Use render_template() Method render template login.html
if __name__ == '__main__':
app.run()
Here we simply pass on the information by obtaining the information filled in by the user to judge whether it is correct , stay login.html The template code is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="{
{ url_for('flash_message') }}" method="post">
<p><input type="text" name="username" placeholder=" enter one user name "></p>
<p><input type="submit" value=" Submit "></p>
</form>
</body>
</html>
Create a form Form and bind the flash_message(), Create text boxes and buttons to complete a simple submission page .
stay index.html In the template , Use get_flashed_messages() Method to get the message , The code is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> home page </title>
</head>
<body>
{% with messages=get_flashed_messages() %} {# Use get_flashed_messages() Method get message #}
{% if messages %}
{% for message in messages %}
{
{ message }}
{% endfor %}
{% endif %}
{% endwith %}
</body>
</html>
Be careful : Use get_flashed_messages() The message obtained by the method is saved in tuples , So you can go through for Loop to get .
Start our flask Program , visit http://127.0.0.1:5000/, As shown in the figure below :

Flask14--- perform flask flash
When we type in admin And click Submit , Will jump to the web , This page displays : Verify success ;
When we enter other characters, click Submit , Will jump to the web , This page displays : Validation failed .
Message flash classification
Use flash() When the method is used , We can pass on category Parameters , Its value can be error( error )、info( Information )、warning( Warning ), The sample code is as follows :
from flask import Flask, render_template, request, flash
app = Flask(__name__)
app.config['SECRET_KEY']='sfasf' # To configure SECRET_KEY, The value is any character
@app.route('/',methods=['GET','POST'])
def flash_message():
if request.method=='POST':
username=request.form.get('username') # Get submitted username value
if username=='admin': # Verify that it is admin
flash(' Verify success ','info') # Use flash Method to pass information , The flash type is :info
return render_template('index.html') # Use render_template() Method render template index.html
else:
flash(' Validation failed ','error') # Use flash Method to pass information , The flash type is :error
return render_template('index.html') # Use render_template() Method render template index.html
return render_template('login.html') # Use render_template() Method render template login.html
if __name__ == '__main__':
app.run()
stay index.html In the template , In the use of get_flashed_messages() when , Delivery required with_categories Parameters , Its value is true, Indicates the receiving flash type , The code is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> home page </title>
</head>
<body>
{% with messages=get_flashed_messages(with_categories=true) %} {# Use get_flashed_messages() Method #}
{% if messages %}
<ul>
{% for category , message in messages %}
<li class="{
{ category }}">{
{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</body>
</html>
Filter flash messages
When we set multiple flashes in the view function , At this time, we can use in the template file get_flashed_messages() Method passing category_filter Parameters to select the flash message we need to display , For example, in the view function above flash(' Verify success ','info') Add the following... Under the code flash() Flash code :
from flask import Flask, render_template, request, flash
app = Flask(__name__)
app.config['SECRET_KEY']='sfasf' # To configure SECRET_KEY, The value is any character
@app.route('/',methods=['GET','POST'])
def flash_message():
if request.method=='POST':
username=request.form.get('username') # Get submitted username value
if username=='admin': # Verify that it is admin
flash(' Verify success ','info') # Use flash Method to pass information , The flash type is :info
flash(' Please don't believe any advertisements ','warning') # Use flash Method to pass information , The flash type is :warning
return render_template('index.html') # Use render_template() Method render template index.html
else:
flash(' Validation failed ','error') # Use flash Method to pass information , The flash type is :error
return render_template('index.html') # Use render_template() Method render template index.html
return render_template('login.html') # Use render_template() Method render template login.html
if __name__ == '__main__':
app.run()
stay index.html In the template file , The code is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> home page </title>
</head>
<body>
{% with messages=get_flashed_messages(category_filter=['warning']) %} {# Use get_flashed_messages() Method #}
{% if messages %}
{% for message in messages %}
{
{ message }}
{% endfor %}
{% endif %}
{% endwith %}
</body>
</html>
Here we filter and select warning Flash type of type , start-up flask Program , visit http://127.0.0.1:5000/,
When we type in admin And click Submit , Will jump to the web , This page displays : Please don't believe any advertisements ;
Be careful : Information cannot be compared with Cookie Big , Otherwise, it will cause flash silence failure .
Okay ,Flask frame —— That's all for the flash message , Thank you for watching. , Let's continue our study in the next article Flask frame ——Flask-WTF Forms : data validation 、CSRF Protect .
official account : White chocolate LIN
The official account is released Python、 database 、Linux、Flask、 automated testing 、Git Etc !
- END -
边栏推荐
猜你喜欢

js 哈希表 01
QT | mouse events and wheel events qmouseevent, qwheelevent

Pytorch tensor list is converted to tensor list of tensor to tensor using torch.stack()

Fastdfs offline deployment (Graphic)

HCIP(12)

Using px2rem does not take effect

Modify MySQL group error expression 1 of select list is not in group

Add CONDA virtual environment env to the Jupiter kernel

Using numpy for elevation statistics and visualization

ONNX Runtime介绍
随机推荐
湖仓一体电商项目(二):项目使用技术及版本和基础环境准备
Leetcode 560 prefix and + hash table
微波技术大作业课设-分立电容电感+微带单枝短截线+微带双枝短截线
4.FTP服务配置与原理
User preferences
Kraken中事件通道原理分析
信号完整性(SI)电源完整性(PI)学习笔记(三十四)100条估计信号完整性效应的经验法则
Research summary of voice self-monitoring pre training model CNN encoder
我为OpenHarmony 写代码,战“码”先锋第二期正式开启!
Using numpy for elevation statistics and visualization
【域泛化】2022 IJCAI领域泛化教程报告
HCIP (01)
[Blue Bridge Cup training 100 questions] scratch Taiji diagram Blue Bridge Cup scratch competition special prediction programming question centralized training simulation exercise question No. 22
HCIP(11)
Reproduce asvspoof 2021 baseline rawnet2
Install MySQL database version 5.7.29 under ubuntu20.04 system
Flask框架——flask-caching缓存
Modify MySQL group error expression 1 of select list is not in group
Electromagnetic field and electromagnetic wave experiment I familiar with the application of MATLAB software in the field of electromagnetic field
Add CONDA virtual environment env to the Jupiter kernel