马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 落叶飞空 于 2017-8-15 23:04 编辑
这一节学习Flask的表单操作实现一个生成微信撤回的昵称
最终效果如下:
网址如下(目前不能在微信中打开):
http://60.205.181.198/wechat
python代码如下:from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from flask_bootstrap import Bootstrap
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
bootstrap = Bootstrap(app)
@app.route('/')
def index():
return render_template('index.html')
class NameForm(FlaskForm):
name = StringField('名字', validators=[DataRequired()])
suffix = StringField('后缀', validators=[DataRequired()])
result = StringField('昵称')
submit = SubmitField('生成')
@app.route('/wechat/', methods=['GET', 'POST'])
def wechat():
form = NameForm()
if form.validate_on_submit():
name = form.name.data
suffix = form.suffix.data
form.result.data = chr(65197) + suffix + chr(65197) + name
return render_template('wechat.html', form=form)
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'),404
if __name__ == '__main__':
app.run(debug=True)
首先引入关键的库文件:from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
然后通过继承表单类定义我们需要的表单:class NameForm(FlaskForm):
name = StringField('名字', validators=[DataRequired()])
suffix = StringField('后缀', validators=[DataRequired()])
result = StringField('昵称')
submit = SubmitField('生成')
其中表单由四部分组成:
名称分别为名字,后缀,昵称的三个文本框,一个名为生成的提交按钮。
然后定义我们的路由:@app.route('/wechat/', methods=['GET', 'POST'])
def wechat():
form = NameForm()
if form.validate_on_submit():
name = form.name.data
suffix = form.suffix.data
form.result.data = chr(65197) + suffix + chr(65197) + name
return render_template('wechat.html', form=form)
在templates文件夹下定义wechat.html:{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>输入名字和后缀点击生成即可!</h1>
</div>
[code]{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}
其中负责通过bootsrap渲染表单。{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}
将微信昵称修改为生成的昵称即可实现撤回出现如下效果:
|