当前位置:网站首页>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 -
边栏推荐
- The idea has been perfectly verified again! The interest rate hike is approaching, and the trend is clear. Take advantage of this wave of market!
- QT | mouse events and wheel events qmouseevent, qwheelevent
- 【策略模式】就像诸葛亮的锦囊
- 4. Children next door will know all kinds of shell symbols {}[], etc
- Multithreading - static proxy mode
- 美国机场围棋风格可视化专题图:ArcGIS Pro版本
- BGP联邦实验
- 代码的表示学习:CodeBERT及其他相关模型介绍
- 云原生IDE:iVX免费的首个通用无代码开发平台
- ONNX(Open Neural Network Exchange)介绍
猜你喜欢
C class library generation, use class library objects to data bind DataGridView

CONDA configures the deep learning environment pytorch transformers

2021 jd.com written examination summary

Wechat applet wxprase contains files that cannot be solved by clicking

1. Shell programming specifications and variables

Disabled and readonly and focus issues

Flask框架——Flask-WTF表单:文件上传、验证码

2021 Niuke written examination summary 02

AI technology stack is too huge! Wu Enda gives career planning: lifelong learning

1.Shell编程规范与变量
随机推荐
Microwave technology homework course design - Discrete capacitance and inductance + microstrip single stub + microstrip double stub
js 集合
Research summary of voice self-monitoring pre training model CNN encoder
The most comprehensive UE4 file operation in history, including opening, reading, writing, adding, deleting, modifying and checking
100W了!
ONNX(Open Neural Network Exchange)介绍
The practice of asynchronous servlet in image service
9.shell文本处理三剑客之awk
8.shell文件处理三剑客之sed
哥廷根大学提出CLIPSeg:一个使用文本和图像prompt能同时作三个分割任务的模型
[strategic mode] like Zhugeliang's brocade bag
使用Numpy进行高程统计及可视化
Wechat applet wxprase contains files that cannot be solved by clicking
JS hash table 01
Visual thematic map of American airport go style: ArcGIS Pro version
2021 牛客网笔试总结 01
Flask框架——Flask-WTF表单:数据验证、CSRF保护
UE4 external open EXE file
7.shell实用的小工具cut等
【蓝桥杯集训100题】scratch太极图 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第22题