Flask 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] ://(?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>
#主程序 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()
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
