码迷,mamicode.com
首页 > Web开发 > 详细

Flask实践——microblog WEB表单 (3)

时间:2018-04-26 17:00:41      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:表单   alt   www.   none   就是   info   分享   github   网站   

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表单 (3)

标签:表单   alt   www.   none   就是   info   分享   github   网站   

原文地址:https://www.cnblogs.com/lnkDel/p/8952957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!