search
HomeBackend DevelopmentPython TutorialFlask application (form processing) in python

The content of this article is about flask application (form processing) in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Why use Flask-WTF?

The request object exposes all request information sent by the client. In particular, request.form has access to form data submitted by POST requests.
Although the support provided by Flask's request object is sufficient to handle web forms, there are still many tasks that can become monotonous and repetitive.
Form HTML code generation and validation of submitted form data are two good examples.

Advantages:

Flask-WTF extension makes processing web forms a more pleasant experience. This extension is a Flask integration that wraps the framework-independent WTForms package.

2. What is form processing?

In a web page, some forms always have to appear in order to interact with users.
flask designed the WTForm form library to make it easier for flask to manage and operate form data.

The most important concepts in WTForm are as follows:

1). Form class, developer-defined forms must inherit from the Form class or its subclasses.
The main function of the Form class is to provide quick access to data in the form through the Field class it contains.

2). Various Field classes, namely fields. Generally speaking, each Field class corresponds to an input HTML tag.
For example, some of the Field classes that come with WTForm, such as BooleanField, correspond to ,
SubmitField corresponds to , etc.

3). Validator class. This class is used to verify the validity of data entered by the user.
For example, the Length validator can be used to verify the length of input data,
FileAllowed verifies the type of uploaded files, etc.

In addition, in order to prevent csfr (cross-site request forgery) attacks, flask requires the app to set secret_key by default before using flask-wtf. The simplest way to configure it is through app.config['SECRET_KEY'] = 'xxxx'.

3. Common Field classes

PasswordField Password field, automatically converts input into small black dots

DateField Text field, the format requirement is datetime .date is the same

IntergerField Text field, the format requirement is an integer

DecimalField Text field, the format requirement is the same as decimal.Decimal

FloatField Text field, the value is a floating point number

BooleanField   Check box, the value is True or False

RadioField   A set of radio button boxes

SelectField   Drop-down list, it should be noted that the choices parameter determines the drop-down option, but it is different from Like the

MultipleSelectField A drop-down list with multiple optional values

Validator verification function

Validator is a verification function that binds a field to a verification function Afterwards, flask will verify the data before receiving the data in the form. If the verification is successful, the data will be received. The verification function Validator is as follows. Specific validators may require different parameters. Here are only some commonly used ones. For more detailed usage, please refer to the source code of the wtforms/validators.py file and see what parameters each validator class requires:

*Basically every validator has a message parameter, which indicates what information is displayed when the input data does not meet the requirements of the validator.

Email Verify the validity of the email address, the required regular pattern is ^. @(12 )$

EqualTo Compare two fields The value is usually used in scenarios such as entering a password twice. You can write the parameter fieldname, but note that it is a string variable pointing to the field name of another field in the same form

IPAddress Verify IPv4 address, parameters Default ipv4=True, ipv6=False. If you want to verify ipv6, you can set these two parameters in reverse.

Length Verify the length of the input string. You can have two parameters min and max to indicate the lower limit and upper limit of the length to be set. Note that the parameter type is a string, not INT!!

NumberRange To verify whether the input number is within the range, you can have two parameters, min and max, to indicate the upper and lower limits of the number. Note that the parameter type is a string, not INT!! Then you can set %(min)s and %( in the message parameter of this validator max)s two formatting parts to tell the front end what this range is. Other validators also have similar tricks, you can refer to the source code.

Optional Skip other validation functions in the same field when there is no input value

Required Required field

Regexp Use regular expression to verify the value, parameter regex='regular pattern'

URL To verify the URL, the required regular pattern is ^[a-z] ://(?P3 )(?P:[0-9] )?(?P/.*)?$

AnyOf Make sure the value is in the list of optional values. The parameters are values ​​(a list of optional values). In particular, when used in conjunction with SelectField, I don't know why the value of the items in SelectField's choices cannot be a number. . Otherwise, even if there are relevant numbers in the values ​​parameter of AnyOf, it cannot be recognized that the current option is a legal option. I suspect NoneOf may have the same trick.

NoneOf Make sure the value is not in the list of optional values

#forms.py文件:用来设定规则
from flask_wtf import FlaskForm
from flask_wtf.file import FileRequired, FileAllowed
from wtforms import StringField, PasswordField, SubmitField, FileField
from wtforms.validators import DataRequired, Length


class LoginForm(FlaskForm):
    name = StringField(
        label="用户名/邮箱/手机号",
        validators=[
            # DataRequired("请输入用户名"),
            Length(3, 20, message="长度不符"),
        ]
    )
    passwd = PasswordField(
        label="密码",
        validators=[
            # DataRequired("请输入密码"),
            Length(3, 20),
        ], )

    file = FileField(
        label="简历",
        validators=[
            FileRequired(),
            FileAllowed(['pdf', 'txt'], 'pdf 能被接收')
        ]
    )
#templates/demo/login.html
nbsp;html>


    <meta>
    <title>Title</title>


    {{ form.hidden_tag() }}     {{ form.name.label }} {{ form.name }}     {{ form.passwd.label }} {{ form.passwd }}     {{ form.file }}     
#主程序
import random
from flask import Flask, redirect, render_template
from forms import LoginForm
from flask_bootstrap import  Bootstrap

app = Flask(__name__)
bootstrap = Bootstrap(app)
app.config['SECRET_KEY'] =  random._urandom(24)

@app.route('/success/')
def success():
    return  "success"

@app.route('/login/', methods=('GET', 'POST'))
def submit():
    # 实例化表单对象;
    form = LoginForm()
    if form.validate_on_submit():
        print(form.data)
        return redirect('/success/')
    return render_template('demo/login.html', form=form)
app.run()

Flask application (form processing) in python

The above is the detailed content of Flask application (form processing) in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

How do you access elements in a Python list?How do you access elements in a Python list?Apr 26, 2025 am 12:03 AM

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor