{% raw %}

Flask 网页表单

原文: https://pythonspot.com/flask-web-forms/

56.md - 图1

Flask web 表单

在本教程中,您将学习如何使用 Flask 进行表单验证。 表单在所有 Web 应用程序中都扮演着重要角色。

我们使用 WTForms,这是用于验证表单的模块。 我们将从一个简单的表格开始,其中包含一个要求输入名称的字段。

CSS 与 Flask

我们使用 Bootstrap 来设置表单的样式。Bootstrap 是流行的 HTML,CSS 和 JS 框架,用于在 Web 上开发响应式,移动优先项目。 它使前端 Web 开发更快,更轻松。 输出将是:

56.md - 图2

Flask wtforms

您可以从 http://getbootstrap.com/getting-started/#download 获取引导文件,并将其解压缩到新目录/static/中。 代码几乎相同,但是模板已更改。 代码:

  1. from flask import Flask, render_template, flash, request
  2. from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
  3. # App config.
  4. DEBUG = True
  5. app = Flask(__name__)
  6. app.config.from_object(__name__)
  7. app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'
  8. class ReusableForm(Form):
  9. name = TextField('Name:', validators=[validators.required()])
  10. @app.route("/", methods=['GET', 'POST'])
  11. def hello():
  12. form = ReusableForm(request.form)
  13. print form.errors
  14. if request.method == 'POST':
  15. name=request.form['name']
  16. print name
  17. if form.validate():
  18. # Save the comment here.
  19. flash('Hello ' + name)
  20. else:
  21. flash('Error: All the form fields are required. ')
  22. return render_template('hello.html', form=form)
  23. if __name__ == "__main__":
  24. app.run()

我们在模板hello.html中添加了 Bootstrap:

  1. <title>Reusable Form Demo</title>
  2. <link rel="stylesheet" media="screen" href="static/bootstrap.min.css">
  3. <link rel="stylesheet" href="static/bootstrap-theme.min.css">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5. <div class="container">
  6. <h2>Flask Web Form</h2>
  7. <form action="" method="post" role="form">
  8. {{ form.csrf }}
  9. <div class="form-group">
  10. <label for="name">Name:</label>
  11. <input type="text" class="form-control" id="name" name="name" placeholder="What's your name?"></div>
  12. <button type="submit" class="btn btn-success">Submit</button>
  13. </form>{% with messages = get_flashed_messages(with_categories=true) %}
  14. {% if messages %}
  15. {% for message in messages %}
  16. {% if "Error" not in message[1]: %}
  17. <div class="alert alert-info">
  18. <strong>Success! </strong> {{ message[1] }}</div>
  19. {% endif %}
  20. {% if "Error" in message[1]: %}
  21. <div class="alert alert-warning">
  22. {{ message[1] }}</div>
  23. {% endif %}
  24. {% endfor %}
  25. {% endif %}
  26. {% endwith %}
  27. </div>

Flask 注册表

我们使用相同的原理来创建注册表,要求输入姓名,电子邮件和密码。 我们更新Form类:

  1. class ReusableForm(Form):
  2. name = TextField('Name:', validators=[validators.required()])
  3. email = TextField('Email:', validators=[validators.required(), validators.Length(min=6, max=35)])
  4. password = TextField('Password:', validators=[validators.required(), validators.Length(min=3, max=35)])
  5. def reset(self):
  6. blankData = MultiDict([ ('csrf', self.reset_csrf() ) ])
  7. self.process(blankData)

我们可以使用以下方法传递变量:

  1. name=request.form['name']
  2. password=request.form['password']
  3. email=request.form['email']

完整代码:

  1. from flask import Flask, render_template, flash, request
  2. from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
  3. # App config.
  4. DEBUG = True
  5. app = Flask(__name__)
  6. app.config.from_object(__name__)
  7. app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'
  8. class ReusableForm(Form):
  9. name = TextField('Name:', validators=[validators.required()])
  10. email = TextField('Email:', validators=[validators.required(), validators.Length(min=6, max=35)])
  11. password = TextField('Password:', validators=[validators.required(), validators.Length(min=3, max=35)])
  12. @app.route("/", methods=['GET', 'POST'])
  13. def hello():
  14. form = ReusableForm(request.form)
  15. print form.errors
  16. if request.method == 'POST':
  17. name=request.form['name']
  18. password=request.form['password']
  19. email=request.form['email']
  20. print name, " ", email, " ", password
  21. if form.validate():
  22. # Save the comment here.
  23. flash('Thanks for registration ' + name)
  24. else:
  25. flash('Error: All the form fields are required. ')
  26. return render_template('hello.html', form=form)
  27. if __name__ == "__main__":
  28. app.run()

使用以下代码更新模板hello.html

  1. <title>Reusable Form Demo</title>
  2. <link rel="stylesheet" media="screen" href="static/bootstrap.min.css">
  3. <link rel="stylesheet" href="static/bootstrap-theme.min.css">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5. <div class="container">
  6. <h2>Flask Web Form</h2>
  7. <form action="" method="post" role="form">
  8. {{ form.csrf }}
  9. <div class="form-group">
  10. <label for="name">Name:</label>
  11. <input type="text" class="form-control" id="name" name="name" placeholder="What's your name?">
  12. <label for="email">Email:</label>
  13. <input type="text" class="form-control" id="email" name="email" placeholder="Your email will be used to contact you.">
  14. <label for="password">Password:</label>
  15. <input type="password" class="form-control" id="password" name="password" placeholder="Enter a password.">
  16. </div>
  17. <button type="submit" class="btn btn-success">Sign Up</button>
  18. </form>{% with messages = get_flashed_messages(with_categories=true) %}
  19. {% if messages %}
  20. {% for message in messages %}
  21. {% if "Error" not in message[1]: %}
  22. <div class="alert alert-info">
  23. <strong>Success! </strong> {{ message[1] }}</div>
  24. {% endif %}
  25. {% if "Error" in message[1]: %}
  26. <div class="alert alert-warning">
  27. {{ message[1] }}</div>
  28. {% endif %}
  29. {% endfor %}
  30. {% endif %}
  31. {% endwith %}
  32. </div>

输出:

56.md - 图3

flask 表单 bootstrap

下载 Flask 示例

WTForms 可以验证电子邮件,密码,数字等等。 有关验证器的列表,请参见:http://wtforms.readthedocs.org/en/latest/validators.html

{% endraw %}