从零开始学Flask框架-005
表单 Flask-WTF
项目结构
pip install flask-wtf
为了实现CSRF 保护,Flask-WTF 需要程序设置一个密钥。Flask-WTF 使用这个密钥生成加密令牌,再用令牌验证请求中表单数据的真伪。
为了增强安全性,密钥不应该直接写入代码,而要保存在环境变量中。
首先,导入flask_wtf库,并从中引入FlaskFrom类,如下所示:
from flask_wtf import FlaskForm
表单的字段、验证函数,需要从wtforms库导入
from wtforms import StringField,SubmitField from wtforms.validators import Required
表单类
表单类
LoginForms.py
from flask_wtf import FlaskForm from wtforms import StringField,SubmitField from wtforms.validators import Required class LoginForm(FlaskForm): name = StringField('请输入你的姓名:') submit = SubmitField('提交')
index.py
from flask import Flask,render_template from flask_bootstrap import Bootstrap from flask import request,url_for from flask_moment import Moment from datetime import datetime from wtforms import StringField,SubmitField from wtforms.validators import DataRequired from app.Views.LoginForm import LoginForm from flask import redirect,session from flask import flash #初始化 app = Flask(__name__) bootstrap = Bootstrap(app) app.config['SECRET_KEY'] = 'hard to guess string' # 初始化实例 moment = Moment(app) #路由,处理URL 和函数之间关系的程序称为路由 @app.route('/',methods=['GET','POST']) #视图函数,函数执行,返回结果 def index(): name = None form = LoginForm() if form.validate_on_submit(): name = form.name.data form.name.data = ''return render_template('index.html',form=form,name=name)) #启动服务器 if __name__ == '__main__': app.run()
把表单渲染成HTML
base.html
{% extends "bootstrap/base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}Flasky{% endblock %} {#包含导航条的程序基模板#} {% block navbar %} <div class="navbar navbar-inverse" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">TEST</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> </ul> </div> </div> </div> {% endblock %} {% block content %} <div class="container"> {% block page_content %}{% endblock %} </div> {% endblock %}
index.html
{% extends "base.html" %} {% block title %}IndexTitle{% endblock %} <div class="container"> {% block page_content %} <h1>Hello Flask!</h1> {# <p>本地时间格式化:{{ moment(current_time).format('YYYY-MM-DD HH:mm:ss') }}.</p>#} {# <p>本地时间格式化:{{ moment(current_time).format('YYYY-MM-DD') }}.</p>#} {# <p>本地时间格式化:{{ moment(current_time).format('YYYY') }}.</p>#} {{ wtf.quick_form(form) }} 你刚输入的姓名是: {{ name }} {% endblock %} </div>
本文来自博客园,作者:江雪独钓翁,转载请注明原文链接:https://www.cnblogs.com/zhouwp/p/11905809.html