Flask Web Development Notes--forms--to be sorted out

Source: Internet
Author: User


Although Flask's request object provides sufficient support for form processing, there are some tasks that are tedious and repetitive. For example, generate HTML code for the form and validate the submission form data.

The FLASK-WTF extension solves these problems. It is based on wtforms

Prevent cross-site request forgery

Cross-site requests forgery (Cross-site request forgery), also known as One-click attack or session riding, is usually abbreviated as CSRF or XSRF, and is a compelling user performing non-native on the currently logged-on Web application The attack method of the intended operation. In contrast to cross-site scripting (XSS), XSS leverages a user's trust in a given website, and CSRF uses the trust of the Web site to the user's Web browser. Wikipedia reference, English Wikipedia reference.

Configuring the encrypted key can prevent CSRF, as follows:

App = Flask (__name__) app.config[' secret_key '] = ' hard to guess string '

The app. config dictionary is a common place within the framework, extensions, or applications that store configuration variables, and methods that support importing from files or environment variables.

Secret_key is a flask and some third-party extended universal keys. Security executions of your keys confirm that each application has a different security key. For security reasons, the key is written in the environment variable, not in the code.

Form class

Each table in FLASK-WTF is represented by a class that inherits from form, and the list of HTML objects for the form is defined in the class. Each HTML object is represented by an object and can have one or more validations. Validation is checking the validity of user input.

From FLASK.EXT.WTF import formfrom wtforms import Stringfield, submitfieldfrom wtforms.validators import Requiredclass Na Meform (Form): name = Stringfield (' What's your name? ', validators=[required ()]) Submit = Submitfield (' Submit ')

The standard HTML objects supported by Wtforms are as follows:

Field type Description
Stringfield Text Field
Textareafield Multiple-line text Field
Passwordfield Password text Field
HiddenField Hidden text Field
Datefield Text Field that accepts a datetime.date value in a given format
Datetimefield Text Field that accepts a datetime.datetime value in a given format
Integerfield Text Field that accepts an integer value
Decimalfield Text Field that accepts a decimal. Decimal value
Floatfield Text Field that accepts a floating-point value
Booleanfield Checkbox with True and False values
Radiofield List of radio buttons
Selectfield Drop-down List of choices
Selectmultiplefield Drop-down List of choices with multiple selection
Filefield File Upload Field
Submitfield Form Submission button
FormField Embed a form as a Field in a container form
FieldList List of fields of a given type

Wtform built-in validation is as follows:

Validator Description
Email Validates an email address
Equalto Compares the values of both fields; Useful when requesting a password to being entered twice for confirmation
IPAddress Validates an IPV4 network address
Length Validates the length of the string entered
Numberrange Validates the value entered is within a numeric range
Optional Allows empty input on the field, skipping additional validators
Required Validates that field contains data
Regexp Validates the input against a regular expression
Url Validates a URL
AnyOf Validates that the input is one of a list of possible values
Noneof Validates that the input is none of a list of possible values
HTML rendering of the form

Render a simple example:

<form method= "POST" > {{Form.name.label}} {{Form.name ()}} {{form.submit ()}}</form>

To add a property:

<form method= "POST" > {{Form.name.label}} {{form.name (id= ' My-text-field ')}} {{form.submit ()}}< /form>

With Flask-bootstrap, the above rendering can be simplified:

{% extends "base.html"%} {% import "bootstrap/wtf.html" as WTF%} {% block title%} flasky{% endblock%}{% block page_content%}<div class= "Page-header" > 

The

hello.py is modified as follows:

from flask import flask, render_templatefrom flask.ext.script import  managerfrom flask.ext.bootstrap import bootstrapfrom flask.ext.moment import  momentfrom flask.ext.wtf import formfrom wtforms import stringfield,  Submitfieldfrom wtforms.validators import requiredapp = flask (__name__) app.config[' Secret_key '] =  ' hard to guess string ' Manager = manager (APP) bootstrap =  bootstrap (APP) moment = moment (APP) Class nameform (Form):    name  = stringfield (' What is your name? ',  validators=[required ()])      Submit = submitfield (' Submit ') @app. ErrorHandler (404) Def page_not_found (e):     return render_template (' 404.html '),  404@app.errorhandler (+) Def internal_server_error (e) :     return render_template (' 500.html '),  500@app.route ('/',  methods=[' GET ',  ' POST ']) Def index ():     name = none    form = nameform ()      if form.validate_on_submit ():         name =  form.name.data        form.name.data =  '      return render_template (' index.html ',  form=form, name=name) if __name__ ==   ' __main__ ':     manager.run ()

The method methods=[' get ', ' POST ', is specified above, and if not specified, GET is used by default. Forms are usually handled by post. Validate_on_submit () call Validate_on_submit () at post

Redirect and user session

As soon as the previous example refreshes, you will forget the username you entered, and for this we add the session and use Post/redirect/get mode to modify the hello.py:

From flask import flask, render_template, session, redirect, url_forfrom  flask.ext.script import managerfrom flask.ext.bootstrap import bootstrapfrom  flask.ext.moment import momentfrom flask.ext.wtf import formfrom wtforms  import StringField, SubmitFieldfrom wtforms.validators import Requiredapp  = flask (__name__) app.config[' Secret_key '] =  ' hard to guess string ' manager =  manager (APP) Bootstrap = bootstrap (APP) moment = moment (APP) Class nameform (Form):     name = stringfield (' What is your name? ',  validators=[ Required ()])     submit = submitfield (' Submit ') @app. ErrorHandler (404) def  Page_not_found (E):     return render_template (' 404.html '),  [email protected] (def internal_s)Erver_error (E):     return render_template (' 500.html '),  [email protected] ('/ ',  methods=[' GET ',  ' POST ']) Def index ():     form = nameform ()     if form.validate_on_submit ():         session[' name '] = form.name.data        return redirect (Url_for (' index '))     return render_template (' index.html ',  form=form, name= Session.get (' name ')) if __name__ ==  ' __main__ ':     manager.run ()

News Feed

Below we add a message when the user name changes.

from flask import flask, render_template, session, redirect, url_for,  flashfrom flask.ext.script import managerfrom flask.ext.bootstrap import  Bootstrapfrom flask.ext.moment import momentfrom flask.ext.wtf import formfrom  wtforms import StringField, SubmitFieldfrom wtforms.validators import  Requiredapp = flask (__name__) app.config[' Secret_key '] =  ' hard to guess  String ' Manager = manager (APP) Bootstrap = bootstrap (APP) moment = moment (APP) class  nameform (Form):     name = stringfield (' What is your name? ',  validators=[required ()])     submit = submitfield (' Submit ') @ App.errorhandler (404) Def page_not_found (E):     return render_template (' 404.html ' ),  [email protected] ($) Def&nbsP;internal_server_error (E):     return render_template (' 500.html '), [email  Protected] ('/',  methods=[' GET ',  ' POST ') def index ():    form =  Nameform ()     if form.validate_on_submit ():         old_name = session.get (' name ')         if old_name  is not None and old_name != form.name.data:             flash (' Looks like you have changed your  name! ')         session[' name '] = form.name.data         return redirect (url_for (' index '))     return render _template (' index.html ',  form=form, name=session.get (' name ')) if __name__ ==  ' __main__ ' :    manager.run () 

Templates/base.html modified as follows:

{% extends  "bootstrap/base.html"  %} {% block title %} Flasky{% endblock %}{% block head %}{{ super ()  }}<link rel= " Shortcut icon " href=" {{ url_for (' static ',  filename= ' favicon.ico ')  }} " type=" Image/x-icon "><link rel=" icon " href=" {{ url_for (' static ',  filename= ' Favicon.ico ')  }} " type=" Image/x-icon ">{% endblock %}{% block navbar %}<div  class= "Navbar navbar-inverse"  role= "Navigation" >    <div class= " Container ">        <div class=" Navbar-header ">             <button type= "button"  class= " Navbar-toggle " data-toggle=" collapse " data-target=". Navbar-collapse ">                 <span class= "Sr-only" >Toggle navigation</span>                 <span class= "Icon-bar" ></span>                 <span  class= "Icon-bar" ></span>                 <span class= "Icon-bar" ></span>             </button>             <a class= "Navbar-brand"  href= "/" >Flasky</a>         </div>        <div class= " Navbar-collapse collapse ">            < Ul class= "Nav navbar-nav";                <li> <a href= "/" >Home</a></li>             </ul>        </div>     </div></div>{% endblock %}{% block content %}<div class= " Container ">    {% for message in get_flashed_messages ()  %}     <div class= "Alert alert-warning" >         <button type= "button"  class= "Close"  data-dismiss= "alert" >&times;</ button>        {{ message }}    </ Div>    {% endfor %}    {% block page_content  %}{% endblock %}</Div>{% endblock %}{% block scripts %}{{ super ()  }}{{ moment.include _moment ()  }}{% endblock %}


Resources
    • Comparison_of_web_application_frameworks

    • Flask Web Framework

    • Next chapter: Flask Web Development Notes--templates

    • Previous chapter: Flask Web Development Notes--templates



Flask Web Development Notes--forms--to be sorted out

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.