Three Web forms of flask Learning

Source: Internet
Author: User
Tags openid

This section Miguel the translation address of the Grinberg tutorial: http://www.pythondoc.com/flask-mega-tutorial/webforms.html

Open source China's: http://www.oschina.net/translate/the-flask-mega-tutorial-part-iii-web-forms

English Original address: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms

PS. Suggest English is better to read English blog directly, because Chinese translation may have problems, and there are problems in the English blog will be modified, but the Chinese translation will not be modified.

About forms: Web Forms are the most basic part of any Web application. We will use forms to allow users to write articles and log in to the application.

First, the configuration

Tutorial: To be able to work with Web Forms, we will use FLASK-WTF, which encapsulates the wtforms and is properly integrated into the Flask.

Because many Flask extensions require a large number of configurations, it is convenient to create a configuration file config.py in the root directory of the microblog folder :

csrf_enabled = True
' you-will-never-guess '

Tutorial: csrf_enabled is configured to activate cross-site request forgery protection. In most cases, you need to activate the configuration to make your application more secure.

The secret_key configuration is required only when CSRF is active, and it is used to create an encrypted token for validating a form. When you write your own application, be sure to set the key that is difficult to guess.

After writing the configuration file, we need to tell flask how to read and use it. Modify app/__init__.py:

 from Import  = Flask (__name__) app.config.from_object ('config')  fromimport views

Second, user login form

Tutorial: In FLASK-WTF, a form is represented as an object, a subclass of theform class. A table list class simply defines a form's field as a variable of a class.

The login form here is not a username/password type, but OpenID. (For this thing is actually I am more confused)

Tutorial: OpenID login requires only a string, called OpenID. We will provide a ' Remember me ' selection box on the form so that users can choose to grow cookies on their web browsers, and when they visit again, the browser can remember their login.

First form (file app/forms.py):

 from  flask.ext.wtf import   Form  from  wtforms import   Stringfield, Booleanfield  from  wtforms.validators import   datarequired  class   LoginForm (Form): OpenID  = Stringfield ( openid   ", validators = [DataRequired ()]) Remember_me 
     = Booleanfield ( "  ' , default = False '  

Note: If you look at the Chinese translation of the tutorial, there is no way to normal execution, the above code is an English blog.

Third, form template

is the HTML layout, the code is as follows (file app/templates/login.html):

<!--extend from base layout -{% extends "base.html"%}{% block content%}<H1>Sign In</H1><formAction=""Method= "POST"name= "Login">{{Form.hidden_tag ()}}<P>Please enter your OpenID:<BR>{{Form.openid (size=80)}}<BR>    </P>    <P>{{Form.remember_me}} Remember Me</P>    <P><inputtype= "Submit"value= " Sign In"></P></form>{% Endblock%}

In all of our templates, we should inherit base.html to ensure the consistency of the layout.

Tutorial: Templates Expect an instantiation from the form object that we just created the surface single class to store as a template parameter, called a form. When we write the view function that renders this template, we will pay special attention to transferring this template parameter into the template.

The Form.hidden_tag () template parameter is replaced with a hidden field that is used to implement the CSRF protection that is activated in the configuration. If you have activated CSRF, this field needs to appear in all of your forms.

The actual fields in our form will also be rendered by the Form object, and you only have to indicate a {{form.field_name}} template parameter where the field should be inserted. Some fields are available with parameters. In our example, we asked the form to generate a 80-character-width OpenID field.

Because we didn't define the submit button in the form, we had to define it as a normal field. The commit field does not actually carry data, so it is not necessary to define it in the form class.

Four, Form view

To see the login page in your browser, you also need a form view with a login page. Modify (file app/views.py):

 fromFlaskImportrender_template, Flash, redirect fromAppImportapp fromFormsImportLoginForm#Index view function suppressed for brevity@app. Route ('/login', methods = ['GET','POST'])deflogin (): Form=LoginForm ()returnRender_template ('login.html', title=' Sign In', Form= form)

One thing the above code does is add a new method to the route decorator. Let Flask understand. This view function supports GET and POST requests. Otherwise, this view function will only respond to GET requests. We need to get the data submitted after the user fills out the form, which is passed from the POST request.

You can login URL http://127.0.0.1:5000/login to see the effect. There is no data to be written, so it is not effective to press the Submit button.

Note: The above is the newly modified part, can not be deleted and added below, as follows:

 fromAppImportapp fromFlaskImportrender_template, Flash, redirect fromFormsImportLoginform@app.route ('/') @app. Route ('/index')defindex (): User= {'Nickname':'Miguel'}#Fake User    returnRender_template ("index.html", title='Home', the user=user) @app. Route ('/login', methods=['GET','POST'])deflogin (): Form=LoginForm ()returnRender_template ('login.html', title=' Sign In', Form= form)

This http://127.0.0.1:5000 the URL to continue to use, otherwise you can only use Http://127.0.0.1:5000/login this URL. Using only the code in the blog http://127.0.0.1:5000 this URL will become 404 Not FOUND

Three Web forms of flask Learning

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.