synopsis
Form operation is one of the most core modules in Web program development , the vast majority of dynamic interactive features are achieved through the form of forms . In this article, we will teach you to achieve a simple form operation.
General Form Submission
Write the form form directly in the create template page.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" method="post"> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" value="Submit"> </form> {% if method == 'GET' %} request method:{{method}} {% elif method == 'POST' %} request method:{{method}} user ID:{{ username }} cryptographic:{{ password }} {% endif %} </body> </html>
Next, get the form data in the view function
from flask import Flask, render_template, request app = Flask(__name__) # index view function @('/login', methods=['GET', 'POST']) def login(): context = dict() if == 'POST': username = ['username'] password = ['password'] print(username, password) context = { 'username': username, 'password': password, } ({'method': }) else: ({'method': }) return render_template('', **context) @('/') def index(): return 'hello' if __name__ == '__main__': (debug=True)
When we click submit, then it will be displayed:
The way to realize the above is to directly use the form of submission. But there is a drawback, if there are many parameters, the background needs to be verified one by one, each time is to receive the parameters first, and then check the parameters, then the workload will be very large, and there will be a csrf attack, then we can use Flask-WTF to create the form, so as to avoid the above drawbacks.
Flask-WTF Basics
The main role of Flask-WTF is to validate the user's request data. We can install this dependency using the pip command, the
pip install flask-wtf
In a flask web application, FlaskForm can be imported from the class FlaskForm because it is defined by the Flask-WTF extension, while fields and functions can be imported directly from the WTForms package, which can support HTML standard fields as shown below.
field | clarification |
---|---|
StringField | Indicates a text field |
TextAreaField | Indicates a multi-line text field |
PasswordField | Indicates a password text field |
HiddenField | Indicates a hidden text field |
DateField | Text field representing the date |
DateTimeFiled | Text field indicating time |
IntegerFiled | Text field representing an integer type |
DecimalField | Text field representing a Decimal type |
FloatFiled | Represents a text field of type Float |
RadioFiled | Indicates a checkbox field |
SelectFiled | Indicates a drop-down list field |
WTForm also includes validators, which validate form fields very conveniently.
field | clarification |
---|---|
DataRequire | Checks if the input field is empty |
Check that the fields conform to the conventions of the mail format | |
IPAddress | Verify the IP address in the input field |
Length | Verify that the length of the string in the input field matches the given length |
NumberRange | Validates text in a given range of input fields |
URL | Verify that the URL is legitimate |
Processing Forms with Flask-WTF
Write two view functions and a form class for registering and jumping to the index page.
from flask import Flask, render_template, redirect, url_for, session from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from import DataRequired, EqualTo app = Flask(__name__) ["SECRET_KEY"] = "xhosd6f982yfhowefy29f" class RegisterForm(FlaskForm): username = StringField(label="Username", validators=[DataRequired('User name cannot be empty')]) password = PasswordField(label="Password.", validators=[DataRequired('Password cannot be empty')]) password_comfirm = PasswordField(label="Confirm password", validators=[DataRequired('Password cannot be empty'), EqualTo('password', 'Two passwords don't match')]) submit = SubmitField(label='Submit') @('/register', methods=['GET', 'POST']) def register(): form = RegisterForm() if form.validate_on_submit(): uname = pwd = pwd_com = form.password_comfirm.data print(uname, pwd, pwd_com) session['username'] = uname return redirect(url_for('index')) return render_template('', form=form) @('/index') def index(): username = ('username', '') return 'hello %s' % username if __name__ == '__main__': (debug=True)
Next write an html template file for user registration use.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" method="post"> {{form.csrf_token}} {{}} <p>{{ }}</p> {% for msg in %} <p>{{ msg }}</p> {% endfor %} {{}} <p>{{ }}</p> {% for msg in %} <p>{{ msg }}</p> {% endfor %} {{form.password_comfirm.label}} <p>{{ form.password_comfirm }}</p> {% for msg in %} <p>{{ msg }}</p> {% endfor %} {{ }} </form> </body> </html>
Flask Message Flashing
In the Flask framework, the method flash() function is to realize the message flash prompt effect.Flask official explanation of flash is to make a non-refreshing response to the user's request. Similar to the Ajax refresh effect.
As a simple example, if a user sends a request through a form and enters an incorrect username or password, the server will return an error message and display it on the form page.
The specific code, as shown below:
from flask import Flask, flash, redirect, render_template, request, url_for app = Flask(__name__) app.secret_key = 'random string' @('/') def index(): return render_template('') @('/login', methods=['GET', 'POST']) def login(): error = None if == 'POST': if ['username'] != 'admin' or ['password'] != 'admin': flash("Incorrect user name or password.") else: flash('Login successful') return redirect(url_for('index')) return render_template('') if __name__ == '__main__': (debug=True)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>log in</title> </head> <body> <form action="" method="post"> <p>username</p> <input type="text" name="username"> <p>password</p> <input type="password" name="password"> <input type="submit" value="Login"> </form> {% for message in get_flashed_messages() %} {% if message %} {{message}} {% endif %} {% endfor %} </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} <p>{{ message }}</p> {% endfor %} {% endif %} {% endwith %} <h3>welcome</h3> <a href="{{url_for('login')}}" rel="external nofollow" >login</a> </body> </html>
The above code implements the URL jump, we will first go to the home page, which contains the link to the login page.
File Upload
To implement file uploads in Flas Web applications is very simple and very similar to passing post and get.The basic process is as follows:
- (1) Save the file uploaded in the client to the object.
- (2) Get the uploaded file name and file object using the object
- (3) Call the method save() in the file object to save the file to the specified directory.
The simple file upload program is shown below:
from flask import Flask, flash, render_template, request app = Flask(__name__) @('/upload', methods=['GET', 'POST']) def upload(): if == 'GET': return render_template('') else: file = ['file'] if file: ( + '.png') return 'Uploaded successfully' @('/') def index(): return render_template('') if __name__ == '__main__': (debug=True)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>File Upload Home</h1> <a href="{{url_for('upload')}}" rel="external nofollow" >File Upload</a> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Click me to upload"> </form> </body> </html>
This program needs to be clicked after the jump to enter the file upload page, the purpose of writing this is only because I am lazy, do not want to enter a large string of url in the browser.
Currently the above program can only upload images!
Another way to write a file upload
The steps for uploading a file in Flask are very simple, you first need an HTML form, set the enctype attribute to "multipart/form-data", and the URL handler will take the file from the[]
object to extract the file and save it to the desired location.
Each uploaded file is first saved to a temporary location on the server and then saved to its final physical location. It is recommended to use thesecure_filename
function gets it.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="/uploader" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Submit"> </form> </body> </html>
from flask import Flask, render_template, request from import secure_filename import os app = Flask(__name__) ['UPLOAD_FLODER']= 'upload/' # Set the path where the file is saved @('/') def upload_file(): return render_template('') @('/uploader', methods=['GET', 'POST']) def uploader(): if == 'POST': f = ['file'] print() ((['UPLOAD_FLODER'], secure_filename())) return 'Uploaded successfully' else: render_template('') if __name__ == '__main__': (debug=True)
to this article on the use of python Flask Web form of introduction to the article is introduced to this , more related to Java Flask form content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future !