当前位置:网站首页>Flame framework - Flame WTF form: file upload, verification code
Flame framework - Flame WTF form: file upload, verification code
2022-07-25 10:53:00 【White chocolate Lin】
Catalog
In the last article , We learned Flask frame ——Flask-WTF Forms : data validation 、CSRF Protect , This article is for us to learn Flask frame ——Flask-WTF Forms : Upload files 、 Verification Code .
Upload files
Flask-WTF The form provides FileField Field to handle file upload , After the form is submitted , Automatically from flask.request.files Extract data from .
The sample code is as follows :
import os
from flask import Flask, render_template
from flask_wtf import FlaskForm, CSRFProtect
from flask_wtf.file import FileField, FileRequired, FileAllowed
app = Flask(__name__)
app.config['SECRET_KEY']='hakhfaskh' # To configure CSRF The key needed , Its value is arbitrary
csrf = CSRFProtect(app) # take CSRF Protection is added to app in
class Myform(FlaskForm):
file = FileField(label=' Upload the user's Avatar ',validators=[FileRequired(), FileAllowed(['jpg','png'])]) # establish FileField Field
@app.route('/',methods=['GET','POST'])
def hello_world():
myform = Myform() # Create a form object
if myform.validate_on_submit(): # Check whether it is a POST Request and whether the request is valid
filename=myform.file.data.filename # Get the passed in file name
filepath=os.path.dirname(os.path.abspath(__file__)) # Get the file path of the current project
savepath=os.path.join(filepath,'static') # Set save file path
myform.file.data.save(os.path.join(savepath,filename)) # Save the file
return ' Submit successfully '
return render_template('file.html', myform=myform) # Use render_template() Method rendering file.html Document and will myform Pass on to file.html in
if __name__ == '__main__':
app.run(debug=True)
To configure CSRF The required key and will CSRF Protection is added to app in , Then create a name called Myform Form class for , In the class, we define FileField File field and use FileRequired File validation functions and FileAllowed File type verification function .
Create a form class object in the view function , Used validate_on_submit() Method to check whether it is a POST Request and whether the request is valid , Get the passed in file name and define the path to save the file , Finally using render_template() Method rendering file.html Document and will myform Pass on to file.html in .
Create a file.html file , Its contents are as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="{
{ url_for('hello_world') }}" method="post" enctype="multipart/form-data">
{
{ myform.csrf_token }} {# Rendering csrf#}
<p>{
{ myform.file.label }}{
{ myform.file }}</p>
<input type="submit" value=" Submit ">
</form>
</body>
</html>
Be careful : Related to documents , Need to be in HTML Form enctype Set to multipart/form-data.
start-up flask project , visit http://127.0.0.1:5000/ And select the file , As shown in the figure below :

Verification Code
Flask-WTF adopt RecaptchaField It also provides support for verification code , The sample code is as follows :
from flask import Flask, render_template
from flask_wtf import FlaskForm, RecaptchaField, CSRFProtect
app = Flask(__name__)
app.config['SECRET_KEY']='hakhfaskh' # To configure CSRF The key needed , Its value is arbitrary
csrf = CSRFProtect(app) # take CSRF Protection is added to app in
class Myform(FlaskForm):
recaptcha = RecaptchaField() # Verification code field
@app.route('/')
def yanzm():
myform=Myform() # Create a form object
return render_template('yanzm.html', myform=myform) # Use render_template() Method rendering yanzm.html Document and will myform Pass on to file.html in
if __name__ == '__main__':
app.run()
To configure CSRF The required key and will CSRF Protection is added to app in , Create a Myform Form class for , In the class, we define RecaptchaField Verification code field , In the view function, we create the form object , Use render_template() Method rendering yanzm.html Document and will myform Pass on to file.html in .
The following parameters need to be configured to use the verification code :
RECAPTCHA_PUBLIC_KEY: Mandatory , Public key ;
RECAPTCHA_PRIVATE_KEY: Mandatory , Private key ;
RECAPTCHA_API_SERVER: Optional , Verification Code API The server ;
RECAPTCHA_PARAMETERS: Optional , One JavaScript(api.js) Dictionary of parameters ;
RECAPTCHA_DATA_ATTRS: Optional , A list of data attribute items https://developers.google.com/recaptcha/docs/display.
Create a yanzm.html, Its contents are as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/" method="post">
{
{ myform.csrf_token }}
{
{ myform.recaptcha }}
</form>
</body>
</html>
start-up flask project , visit http://127.0.0.1:5000/, Found nothing to show , This is because RecaptchaField() Field needs to call Google's verification code API, And call Google's verification code API Need to climb over the wall , We didn't climb over the wall , So nothing shows , As shown in the figure below :

Use RecaptchaField() The verification code field needs to cross the wall , Then we won't use it , We draw the verification code ourselves .
Here we draw the verification code using pillow Graphics library , It executes the following code installation :
pip install pillow
Install well pillow after , Let's create a name uitl.py file , Its function is to draw our graphic verification code , The code is as follows :
import random
from PIL import Image, ImageFont, ImageDraw
# Customize get_color Method , Get three random numbers and save them in tuples
def get_color():
return (random.randint(0,255),random.randint(0,255),random.randint(0,255))
# Customize generate_image Method to draw a picture verification code
def generate_image(4):
size=(130,50) # Set the size of the verification code
im=Image.new('RGB',size,color=get_random_color()) # Create a verification code background
font=ImageFont.truetype('C:\Windows\Fonts/simsun.ttc',size=40) # Set verification code font
draw=ImageDraw.Draw(im) # establish ImageDraw object
code='' # Set the verification code value
s='abcdefghijklmnopqrstuvwxyz123456' # Set the value range of the verification code
for i in range(4): # draw 4 Digit verification code value
c=random.choice(s) # Random in s The value of
code+=c # Put the obtained value in the verification code
draw.text((9+random.randint(4,7)+20*i,random.randint(4,7)),text=c,fill=get_random_color(),font=font) # Write the verification code value in the verification code background
im.show()
return im ,code # Return the image and verification code value
We customize get_color Method gets a three bit random number stored in a tuple and returns , Customize it again generate_image() Method to draw a picture verification code , Set the value range of the verification code 、 Background image size font, etc , And randomly obtain the verification code value and write it into the verification code background .
You can do it according to pillow Library documentation to add some interference lines to the verification code , In this way, the simple version of the graphic verification code is made , As shown in the figure below :

Here we draw 4 Character image verification code , The code generation of image verification code has been written , Next we write flask Project to use the verification code , The sample code is as follows :
from flask import Flask, render_template, session
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, ValidationError
app = Flask(__name__)
app.config['SECRET_KEY']='hakhfaskh' # To configure CSRF The key needed , Its value is arbitrary
csrf = CSRFProtect(app) # take CSRF Protection is added to app in
class Myform(FlaskForm): # Create a form class
recaptcha = StringField() # Create a text field
def validate_recaptcha(self, data): # Custom validation
input_code=data.data # The value of the entered verification code
code=session.get('valid') # obtain session Of valid value
if input_code.lower()!=code.lower(): # Convert the verification code value to lowercase and judge whether the input verification code and the image verification code value are consistent
raise ValidationError(' Verification code error ') # Throw an error
@app.route('/',methods=['GET','POST'])
def yanzm():
myform=Myform() # Create form class objects
if myform.validate_on_submit(): # Check whether it is a POST Request and whether the request is valid
return ' Verify success '
return render_template('yanzm.html', myform=myform) # Use render_template() Method rendering yanzm.html Document and will myform Pass on to file.html in
if __name__ == '__main__':
app.run()
Set up CSRF Protect , Create a form class to use StringField() Text fields and custom validation functions , Then create a form class object in the view function , Use validate_on_submit() Method to check whether it is a POST Request and whether the request is valid , Use render_template() Method rendering yanzm.html Document and will myform Pass on to file.html in .
Is this ok ? Here we also need to create a view function to get the image verification code , The code is as follows :
from util import generate_image # Import generate_image
@app.route('/image')
def get_image():
im,code=generate_image() # Get the verification code image and value
buffer=BytesIO() # take image Object to binary
im.save(buffer,"JPEG") # Save in binary form as JPEG Format
buf_bytes=buffer.getvalue() # Read binary verification code
session['valid']=code # Save to session in , Control the expiration time of the verification code
response=make_response(buf_bytes) # structure response object
response.headers['Content-Type']='image/jpg' # Custom request header
return response
In the view function , We call generate_image() Method to obtain the verification code image and value and save the image in binary form as JPEG Format , Generally, the verification code has an expiration time , So we use session Control the implementation time of the verification code , Use make_response() structure response Object to customize the request header for the verification code image .
Next we write yanzm.html file , The code is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/" method="post">
{
{ myform.csrf_token }} {# Rendering csrf#}
{
{ myform.recaptcha }}<img src="{
{ url_for('get_image') }}" alt="" id="img">
<p>{
{ myform.recaptcha.errors.0 }}</p>
<input type="submit" value=" Submit ">
</form>
</body>
</html>
In general , As long as we click the image verification code, it will refresh , So we can add the following code to control the refresh of the image verification code :
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
$('#img').click(function (){
$(this).attr('src',"{
{ url_for('get_image') }}?ran="+Math.random());
})
</script>
Here we call Baidu jquery And add a click event for the verification code .
Okay , In this way, we have successfully drawn our image verification code , start-up flask project , visit http://127.0.0.1:5000/, As shown in the figure below :

When we input correctly and click Submit , It will show that the verification is successful , When we input incorrectly and click Submit , The verification code error will be displayed .
Okay ,Flask frame ——Flask-WTF Forms : Upload files 、 That's all for the verification code , Thank you for watching. , Next article study Flask frame ——Flask-Mail mail .
official account : White chocolate LIN
The official account is released Python、 database 、Linux、Flask、 automated testing 、Git Etc !
- END -
边栏推荐
- 3. Believe you can understand! Circular statements and functions of shell scripts, arrays, bubble sorting
- 8. SHELL file processing Three Musketeers sed
- 软件测试技术之跨平台的移动端UI自动化测试(上)
- 5.这简单的 “echo” 用法隔壁小孩能不会吗!
- After switching the shell command line terminal (bash/zsh), CONDA cannot be used: command not found
- C# 类库的生成,使用类库对象对DataGridView 进行数据绑定
- 【蓝桥杯集训100题】scratch太极图 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第22题
- Wechat applet wxprase contains files that cannot be solved by clicking
- Using px2rem does not take effect
- Basic experiment of microwave technology - Filter Design
猜你喜欢

After switching the shell command line terminal (bash/zsh), CONDA cannot be used: command not found
![[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](/img/d5/56173050f62d5b6fa336ff8d257fca.png)
[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

云原生IDE:iVX免费的首个通用无代码开发平台

2.shell脚本之条件语句

2. Conditional statements of shell script

VLAN configuration and application (take Huawei ENSP as an example)

js 双向链表 02

2021 致景笔试总结

2021 jd.com written examination summary

Wechat applet wxprase contains files that cannot be solved by clicking
随机推荐
[strategic mode] like Zhugeliang's brocade bag
8.shell文件处理三剑客之sed
3.信你能理解的!shell脚本之循环语句与函数,数组,冒泡排序
推荐系统-协同过滤在Spark中的实现
Pytoch separates tensor by the value of one dimension of tensor (simple)
HCIA实验(08)
BGP联邦实验
HCIP实验(02)
Gan, why '𠮷 𠮷'.Length== 3 ??
HCIP(12)
美国机场围棋风格可视化专题图:ArcGIS Pro版本
Idea overall font size modification
1. Shell programming specifications and variables
HCIP实验(03)
Flask框架——消息闪现
6. PXE combines kickstart principle and configuration to realize unattended automatic installation
2. Introduce the deployment of lamp platform +discuz Forum
Wechat applet wxprase contains files that cannot be solved by clicking
The most comprehensive UE4 file operation in history, including opening, reading, writing, adding, deleting, modifying and checking
HCIP实验(04)