1. CSRF Protection
from = Flask (__name__) app.config['secret_key' Secret_key string'
The app. Config dictionary can be used to store configuration variables for frameworks, extensions, and programs themselves.
Use the standard dictionary syntax to add configuration values to the App. Config object
Secret_key configuration variable is a universal key
PS: To enhance security, keys should not be written directly to the code, but stored in environment variables
2. Form Class
When using FLASK-WTF, the Web form is represented by a class this inherits from class form.
The class defines the list of fields in the form, and each represented by an object.
Eachfield object can have one or more validators attached; validators is functions that check whether the input Submi Tted by the user is valid.
from flask.ext.wtf import Form from wtforms import Stringfield, Submitfield from wtforms.validators import Required class Nameform (Form): Name = Stringfield ( " , Validators=[required (), Length (1, 16 = Submitfield ( " submit Span style= "color: #800000;" > ' )
The Stringfield class represents a <input> element with a type= "text" attribute.
The Submitfield class represents a <input> element with a type= "submit" attribute.
The first argument to the field constructors are the label that would be used when rendering the form to HTML.
The optional validators argument included in the Stringfield constructor defines a list of checkers that'll be applied t o The data submitted by the user before it is accepted.
The Required () validator ensures that the field was not submitted empty.
Wtforms Standard HTML fields
Wtforms validators
3. Rendering the form into HTML
Suppose a view function passes a Nameform instance through a parameter form into a template, a simple form can be generated in the template, as shown below
<method= "Post"> {{Form.name.label}}{{form.name ()}} {{Form.submit ()}} </ form >
To improve the look of the form, any arguments sent into the calls so render the fields is converted into HTML attribut Es for the field;
So, for example, you can give the field ID or class attributes and then define CSS styles:
<method= "POST">{{ Form.name.label}} {{form.name (id= ') My-text-field ')}} {{form.submit ()}}</form>
Flask-bootstrap can render an entire FLASK-WTF form using pre-defined form styles in Bootstrap
{% import "bootstrap/wtf.html" as WTF%} {{wtf.quick_form (form)}}
4. Working with forms in view functions
@app. Route ('/', methods=['GET','POST'])defindex (): Name=None Form=Nameform ()ifform.validate_on_submit (): Name=Form.name.data Form.name.data="' returnRender_template ('index.html', Form=form, Name=name)
The methods parameter added in the App.route decorator tells Flask to register this view function as a handler for Get and POST requests in the URL map. If you do not specify the methods parameter, only the view function is registered as a handler for the GET request.
If the data can be accepted by all validation functions after the form is submitted, the return value of the Validate_on_submit () method is True, otherwise False is returned. The return value of this function determines whether the form is re-rendered or the data submitted by the form is processed.
When a user accesses a program for the first time, the server receives a GET request with no form data, so Validate_on_submit () returns FALSE.
The content of the IF statement is skipped, processing the request through the render template, and passing in the Form object and the name variable with the value None as the parameter. The user will see a form displayed in the browser.
After the user submits the form, the server receives a POST request that contains the data. Validate_on_submit () invokes the Required () validation function that is attached to the name field.
If the name is not empty, it can be verified and validate_on_submit () returns TRUE. The name entered by the user can now be obtained from the Data property of the field.
In the If statement, empty the form field by assigning the name to the local variable name, and then setting the Data property to an empty string.
The last line calls the Render_template () function to render the template, but this time the value of the parameter name is the name entered in the form, so a welcome message is displayed for that user.
5. Redirect (redirects) and user sessions (users session)
Redirection (redirect) is often used as a response to a POST request, rather than using a regular response, that is, post/redirect/get pattern
fromFlaskImportFlask, Render_template, session, redirect, Url_for@app.route ('/', methods=['GET','POST'])defindex (): Form=Nameform ()ifform.validate_on_submit (): seesion['name'] =Form.name.datareturnRedirect (Url_for ('Index')) returnRender_template ('index.html', Form=form, Name=session.get ('name'))
6. Flash messages
Once the request is complete, it is sometimes necessary to let the user know that the state has changed (can be a confirmation message, warning, or error alert)
For example, after a user submits a login form with an error, the response from the server re-renders the login form and displays a message on the form indicating that the user name or password is incorrect.
fromFlaskImportFlask, Render_template, seesion, redirect, Url_for, Flash@app.route ('/', method=['GET','POST'])defindex (): Form=Nameform ()ifform.validate_on_submit (): Old_name= Session.get ('name') ifOld_name is notNone andOld_name! =Form.name.data:flash ('Looks you have changed your name!') session['name'] =Form.name.datareturnRedirect (Url_for ('Index')) returnRender_template ('index.html', Form= form, name = Seesion.get ('name'))
Only the Flash () function is called and the message cannot be displayed, and the template used by the program renders the messages.
Flask opens the Get_flashed_messages () function to the template, which is used to fetch and render the message.
The message obtained by the Get_flashed_messages () function is not returned again on the next call, so the Flash message is displayed only once and then disappears.
{% block content%}<Divclass= "Container">{% for message in get_flashed_messages ()%}<Divclass= "Alert Alert-warning"> <Buttontype= "button"class= "Close"Data-dismiss= "Alert">×</Button>{{message}}</Div>{% endfor%} {% block page_content%}{% endblock%}</Div>{% Endblock%}
Using loops in a template is because a message is generated each time a flash () function is called in a previous request loop, so multiple messages may be queued for display.
Put down this section of code
fromFlaskImportFlask, Render_template, session, redirect, Url_for, Flash fromFlask.ext.scriptImportManager fromFlask.ext.bootstrapImportBootstrap fromFlask.ext.momentImportmoment fromFlask.ext.wtfImportForm fromWtformsImportStringfield, Submitfield fromWtforms.validatorsImportRequiredapp= Flask (__name__) app.config['Secret_key'] ='Hard to guess string'Manager=Manager (APP) Bootstrap=Bootstrap (APP) moment=Moment (APP)classNameform (Form): Name= Stringfield ('What is your name?', validators=[Required ()]) Submit= Submitfield ('Submit') @app. ErrorHandler (50U)defPage_not_found (E):returnRender_template ('404.html'), 404@app. ErrorHandler (500)defInternal_server_error (E):returnRender_template ('500.html'), 500@app. Route ('/', methods=['GET','POST'])defindex (): Form=Nameform ()ifform.validate_on_submit (): Old_name= Session.get ('name') ifOld_name is notNone andOld_name! =Form.name.data:flash ('Looks you have changed your name!') session['name'] =Form.name.datareturnRedirect (Url_for ('Index')) returnRender_template ('index.html', Form=form, Name=session.get ('name'))if __name__=='__main__': Manager.run ()
2015-05-21
Three--web forms of flask learning