Flask实践——microblog WEB表单

Posted lnkDel

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask实践——microblog WEB表单 相关的知识,希望对你有一定的参考价值。

WEB表单

  1. 配置
    1. 创建microblog/config.py
      CSRF_ENABLED = True
      SECRET_KEY = \'you-will-never-guess\'
    2. 修改app/__init__.py
      from flask import Flask
      
      app = Flask(__name__)
      app.config.from_object(\'config\')
      
      from app import views
  2. 登录表单
    1. 创建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(\'remember_me\', default=False)
    2. 创建app/templates/login.html
      <!-- 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 %}
    3. 表单视图 app/views.py添加route
      from flask import render_template
      from app import app
      from .forms import LoginForm
      
      # index view function suppressed for brevity
      
      @app.route(\'/login\', methods = [\'GET\', \'POST\'])
      def login():
          form = LoginForm()
          return render_template(\'login.html\',
              title = \'Sign In\',
              form = form)
    4. 接收表单数据 修改上述route
      @app.route(\'/login\', methods = [\'GET\', \'POST\'])
      def login():
          form = LoginForm()
          if form.validate_on_submit():
              flash(\'Login requested for OpenID="\' + form.openid.data + \'", remember_me=\' + str(form.remember_me.data))
              return redirect(\'/index\')
          return render_template(\'login.html\',
              title = \'Sign In\',
              form = form)

      修改base.html

      <html>
        <head>
          {% if title %}
          <title>{{title}} - microblog</title>
          {% else %}
          <title>microblog</title>
          {% endif %}
        </head>
        <body>
          <div>Microblog: <a href="/index">Home</a></div>
          <hr>
          {% with messages = get_flashed_messages() %}
          {% if messages %}
          <ul>
          {% for message in messages %}
              <li>{{ message }} </li>
          {% endfor %}
          </ul>
          {% endif %}
          {% endwith %}
          {% block content %}{% endblock %}
        </body>
      </html>
    5. 字段验证
      在模板中,通常情况下,任何需验证字段都会把错误信息放入form.field_name.errors ,遍历此对象即可显示
      {% for error in form.openid.errors %}
          <span style="color: red;">[{{ error }}]</span>
      {% endfor %}<br>
  3. OpenID处理
      目前Google、Yahoo、Flickr都已经支持OpenID,鉴于国内网络环境,这里使用http://www.openid.org.cn/。进入该网站,注册自己的帐号,然后使用OpenID来登录我的microblog。
           修改config.py,添加OpenID配置列表
    OPENID_PROVIDERS = [
        { \'name\': \'Google\', \'url\': \'https://www.google.com/accounts/o8/id\' },
        { \'name\': \'Yahoo\', \'url\': \'https://me.yahoo.com\' },
        { \'name\': \'AOL\', \'url\': \'http://openid.aol.com/<username>\' },
        { \'name\': \'Flickr\', \'url\': \'http://www.flickr.com/<username>\' },
        { \'name\': \'MyOpenID\', \'url\': \'http://lnkdel.openid.org.cn/\' }]

        修改登录route,文件app/views.py

    @app.route(\'/login\', methods=[\'GET\', \'POST\'])
    @oid.loginhandler
    def login():
        if g.user is not None and g.user.is_authenticated:
            return redirect(url_for(\'index\'))
        form = LoginForm()
        if form.validate_on_submit():
            session[\'remember_me\'] = form.remember_me.data
            return oid.try_login(form.openid.data, ask_for=[\'nickname\', \'email\'])        
        return render_template("login.html",
                               title=\'Sign In\',
                               form=form,
                               providers=app.config[\'OPENID_PROVIDERS\'])

        修改app/templates/login.html

    <!-- extend base layout -->
    {% extends "base.html" %}
    
    {% block content %}
    <script type="text/javascript">
    function set_openid(openid, pr)
    {
        u = openid.search(\'<username>\')
        if (u != -1) {
            // openid requires username
            user = prompt(\'Enter your \' + pr + \' username:\')
            openid = openid.substr(0, u) + user
        }
        form = document.forms[\'login\'];
        form.elements[\'openid\'].value = openid
    }
    </script>
    <h1>Sign In</h1>
    <form action="" method="post" name="login">
        {{ form.hidden_tag() }}
        <p>
            Please enter your OpenID, or select one of the providers below:<br>
            {{ form.openid(size=80) }}
            {% for error in form.openid.errors %}
              <span style="color: red;">[{{error}}]</span>
            {% endfor %}<br>
            |{% for pr in providers %}
              <a href="javascript:set_openid(\'{{ pr.url }}\', \'{{ pr.name }}\');">{{ pr.name }}</a> |
            {% endfor %}
        </p>
        <p>{{ form.remember_me }} Remember Me</p>
        <p><input type="submit" value="Sign In"></p>
    </form>
    {% endblock %}

    下面就是我们登录界面的一个截图:

最后,下一篇将引入数据库来描述Flask中数据库的使用。

源码

以上是关于Flask实践——microblog WEB表单 的主要内容,如果未能解决你的问题,请参考以下文章

flask表单操作

《Flask Web开发——基于Python的Web应用开发实践》一字一句上机实践(上)

Flask 教程 第十六章:全文搜索

Flask 教程 第十七章:Linux上的部署

flask学习笔记(-Web 表单)

flask web表单