The method of using flag WTF to verify uploaded files


Using flag WTF to verify the uploaded files

  1. When defining the validation form class, filefield should be used for fields of file type, that is wtforms.FileField 。
  2. The verifier needs to start from flash_ wtf.file Import. flask_ wtf.file.FileRequired And flask_ wtf.file.FileAllowed
  3. flask_ wtf.file.FileRequired Is used to verify that the file upload cannot be empty.
  4. flask_ wtf.file.FileAllowed The suffix name used to verify the uploaded file, such as common image suffixes. JPG and. PNG and. GIF.
  5. In the view function, you need to use from werkzeug.datastructures Import combined multiple Dict request.form And request.files To merge.
  6. Finally, the form validation object. Validate () is used to verify.

upload.html Document:

<!DOCTYPE html> 
<html lang="en"> 
<meta charset="UTF-8"> 
< title > upload file 
 <form action="" method="post" enctype="multipart/form-data"> 
 <td>Head image:</td> 
 <td><input type="file" name="pichead"></td> 
 <td><input type="text" name="desc"></td> 
 <td>< input type = submit "value = submit" ></td> 
</html> Document:

from wtforms import Form,FileField,StringField 
from wtforms.validators import InputRequired
from flask_wtf.file import FileRequired,FileAllowed 

class UploadForm(Form): 
 pichead = FileField(validators=[FileRequired(),FileAllowed(['jpg','png','gif'])])
 desc = StringField(validators=[InputRequired()])

Python startup file:

from flask import Flask,request,render_template 
import os 
from werkzeug.utils import secure_filename 
from formscheck import UploadForm 
from werkzeug.datastructures import CombinedMultiDict 

app = Flask(__name__) 

UPLOAD_PATH = os.path.join(os.path.dirname(__file__),'images') 

#Using flag WTF to verify the uploaded files 
def upload(): 
 if request.method == 'GET': 
 return render_template('upload.html') 
 form = UploadForm(CombinedMultiDict([request.form,request.files])) 
 if form.validate(): 
  # desc = request.form.get("desc") 
  # pichead = request.files.get("pichead") 
  desc = 
  pichead = 
  filename = secure_filename(pichead.filename),filename)) 
  Return 'file uploaded successfully' 
  Return "file upload failed." 

if __name__ == '__main__':

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

How to share queues with hypertools 2.5

Share queue with swote To realize asynchronous IO between processes, the general idea is to use redis queue. Based on the development of swote, the queue can also be realized through high-performance shared memory table. Copy the code from the HTTP tutorial on swoole’s official website, and configure four worker processes to simulate multiple producers […]