# Flask Day 2

2016年2月16日

To handle web forms we use Flask-WTF . So we need to write a config file (file `config.py`):

    1
    2

    WTF_CSRF_ENABLED = True
    SECRET_KEY = 'you-will-never-guess'

And then you need to use this config (file `app/__init__.py`):

    1
    2
    3
    4
    5
    6

    from flask import Flask

    app = Flask(__name__)
    app.config.from_object('config')

    from app import views

Let’s build a simple form (file `app/forms.app`):

    1
    2
    3
    4
    5
    6
    7

    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('remember_me', default=False)

The `DataRequired()` is a validator that checks the field is empty or not.

After that, we need a HTML page to show the form (file `app/templates/login.html`):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

    <!-- extend from base layout -->
    {% extends "base.html" %}

    {% block content %}
      <h1>Sign In</h1>
      <form action="" 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><input type="submit" value="Sign In"></p>
      </form>
    {% endblock %}

The final step is to code a view function that renders the template and receiving data from form (file `app/views.py`):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    from flask import render_template, flash, redirect
    from app import app
    from .forms import LoginForm

    # index view function suppressed for brevity

    app.route('/login', methods=['GET', 'POST'])
    def login():
        form = LoginForm()
        if form.validate_on_submit():
            flash('Login requested for OpenID="%s", remember_me=%s' %
                  (form.openid.data, str(form.remember_me.data)))
            return redirect('/index')
        return render_template('login.html',
                               title='Sign In',
                               form=form)