In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to use Flask Web forms in python". In daily operation, I believe many people have doubts about how to use Flask Web forms in python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use Flask Web forms in python". Next, please follow the editor to study!
General form submission
Write the form form directly in the create template login.html page.
Login.html
Document {% if method = = 'GET'%} request method: {{method}} {% elif method = =' POST'%} request method: {{method}} user name: {{username}} password: {{password}} {% endif%}
Next, get the form data in the view function
Login.py
From flask import Flask, render_template, requestapp = Flask (_ _ name__) # index View function @ app.route ('/ login', methods= ['GET',' POST']) def login (): context = dict () if request.method = = 'POST': username = request.form [' username'] password = request.form ['password'] print (username, password) context = {' username': username 'password': password,} context.update ({' method': request.method}) else: context.update ({'method': request.method}) return render_template (' login.html', * * context) @ app.route ('/') def index (): return 'hello'if _ _ name__ = =' _ main__': app.run (debug=True)
When we click submit, it displays:
The above implementation is to directly use the form submission. But there is a drawback, if there are a lot of parameters, the background also needs to verify one by one, each time is to receive the parameters, and then check the parameters, the workload will be very huge, and there will be csrf attacks, then we can use Flask-WTF to create the form, so as to avoid the above disadvantages.
Flask-WTF Foundation
The main function of Flask-WTF is to validate the user's request data. We can install the dependency using the pip command
Pip install flask-wtf
In flask web programs, because the class FlaskForm is defined by the Flask-WTF extension, you can import FlaskForm from flask.wtf. Fields and functions can be imported directly from the WTForms package, and the WTForms package can support HTML standard fields as shown below.
Field description StringField represents text field TextAreaField represents multiline text field PasswordField represents password text field HiddenField represents hidden text field DateField represents date text field DateTimeFiled represents time text field IntegerFiled represents integer type text field FloatFiled represents Decimal type text field RadioFiled represents Float type text field SelectFiled represents drop-down list field
WTForm also includes a validator, which validates form fields, which is convenient.
Field description DataRequire checks whether the entered field is empty Email checks whether the field conforms to the convention of message format IPAddress validates the IP address in the input field Length verifies that the string length in the input field meets the given length NumberRange verifies the text in the input field within a given range URL verifies that it is a legitimate URL uses Flask-WTF to process forms
Write two view functions and a form form class to register and jump to the index page.
Login.py
From flask import Flask, render_template, redirect, url_for, sessionfrom flask_wtf import FlaskFormfrom wtforms import StringField, PasswordField, SubmitFieldfrom wtforms.validators import DataRequired, EqualToapp = Flask (_ _ name__) app.config ["SECRET_KEY"] = "xhosd6f982yfhowefy29f" class RegisterForm (FlaskForm): username = StringField (label= "username", validators= [DataRequired ('username 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',' password is inconsistent')]) submit = SubmitField (label=' submit') @ app.route ('/ register', methods= ['GET'') 'POST']) def register (): form = RegisterForm () if form.validate_on_submit (): uname = form.username.data pwd = form.password.data pwd_com = form.password_comfirm.data print (uname, pwd, pwd_com) session [' username'] = uname return redirect (url_for ('index')) return render_template (' register.html' Form=form) @ app.route ('/ index') def index (): username = session.get ('username','') return 'hello% s'% usernameif _ _ name__ = ='_ main__': app.run (debug=True)
Next, write a html template file for users to register for use.
Register.html
Document {{form.csrf_token}} {{form.username.label}}
{{form.username}}
{% for msg in form.username.errors%}
{{msg}}
{% endfor%} {{form.password.label}}
{{form.password}}
{% for msg in form.password.errors%}
{{msg}}
{% endfor%} {{form.password_comfirm.label}}
{{form.password_comfirm}}
{% for msg in form.password.errors%}
{{msg}}
{% endfor%} {{form.submit}} Flask message flashes
In the Flask framework, the function of the method flash () is to achieve the effect of message flash prompts. Flask's official explanation for flash is a non-refresh response to a user's request. Similar to the refresh effect of Ajax.
To take a simple example, after the user sends the request through the form, if the user name or password is entered incorrectly, the server will return the wrong message and display it on the form page.
The specific code is as follows:
Login.py
From flask import Flask, flash, redirect, render_template, request, url_forapp = Flask (_ _ name__) app.secret_key = 'random string'@app.route (' /') def index (): return render_template ('index.html') @ app.route (' / login', methods= ['GET') 'POST']) def login (): error = None if request.method = =' POST': if request.form ['username']! =' admin' or request.form ['password']! =' admin': flash ("wrong username or password") else: flash ('login successful') return redirect (url_for ('index')) Return render_template ('login.html') if _ _ name__ = =' _ main__': app.run (debug=True)
Login.html
Log in
Username
Password
{% for message in get_flashed_messages ()%} {% if message%} {{message}} {% endif%} {% endfor%}
Index.html
Document {% with messages = get_flashed_messages ()%} {% if messages%} {% for message in messages%}
{{message}}
{% endfor%} {% endif%} {% endwith%} welcome login
The above code implements the URL jump, we will first go to the home page, which contains a link to the login page.
File upload
Uploading files in Flas Web programs is very simple, which is very similar to passing post and get. The basic process is as follows:
(1) Save the file uploaded on the client to the flask.request.files object.
(2) use flask.request.files object to obtain the uploaded file name and file object
(3) call the method save () in the file object to save the file to the specified directory.
The simple file upload procedure is as follows:
Upload.py
From flask import Flask, flash, render_template, requestapp = Flask (_ _ name__) @ app.route ('/ upload', methods= ['GET' 'POST']) def upload (): if request.method =' GET': return render_template ('upload.html') else: file = request.files [' file'] if file: file.save (file.name + '.png') return 'uploaded successfully' @ app.route ('/') def index (): return render_template ('index.html' ) if _ _ name__ = ='_ main__': app.run (debug=True)
Index.html
Document File upload Home File upload
Upload.html
File upload
This program needs to click to jump to enter the file upload page, this is just because I am lazy, do not want to enter a long string of url in the browser.
At present, the above program can only upload pictures!
Another way to upload files
The steps for uploading files in Flask are very simple. First, you need a HTML form and set the enctype property to "multipart/form-data". The URL processor extracts the file from the request.file [] object and saves it to the desired location.
Each uploaded file is first saved to a temporary location on the server, and then saved to the final actual location. It is recommended to use the secure_filename function to get it.
Index.html
Document
Upload.py
From flask import Flask, render_template, requestfrom werkzeug.utils import secure_filenameimport osapp = Flask (_ _ name__) app.config ['UPLOAD_FLODER'] =' upload/' # set the path to save the file @ app.route ('/') def upload_file (): return render_template ('upload.html') @ app.route (' / uploader', methods= ['GET') 'POST']) def uploader (): if request.method =' POST': f = request.files ['file'] print (request.files) f.save (os.path.join (app.config [' UPLOAD_FLODER']) Secure_filename (f.filename)) return 'upload successfully' else: render_template ('upload.html') if _ _ name__ =' _ _ main__': app.run (debug=True) to this point The study on "how to use Flask Web forms in python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.