Flask做轻量级的Web服务开发很方便, 只需要pip install所需安装包即可,依赖的较少且容易获取。简单的程序如下所示:
#!/usr/bin/env python
from flask import Flask
from flask_wtf import FlaskForm
from flask import render_template, request
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from wtforms import Form, BooleanField, StringField, PasswordField, validators
app = Flask(__name__)
class NameForm(FlaskForm):
name = StringField('What is your name?', validators=[Required()])
submit = SubmitField('Submit')
@app.route('/')
def index():
form = NameForm()
if form.validate_on_submit():
print form.name.data
#return '<h1>Hello World!</h1>'
class RegistrationForm(FlaskForm):
username = StringField('Username', [validators.Length(min=4, max=25)])
email = StringField('Email Address', [validators.Length(min=6, max=35)])
password = PasswordField('New Password', [
validators.DataRequired(),
validators.EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if request.method == "POST":
print request.form["username"]
'''
if form.validate_on_submit():
print form.username.data
flash(form.username.data)
'''
return render_template('register.html', form=form, title = 'register')
@app.route('/user/<name>')
def user(name):
#return '<h1>Hello, %s!</h1>' % name
return render_template('hello.html', name=name)
if __name__ == '__main__':
app.config.from_object('config')
app.run(debug=True, host= '0.0.0.0', port = 8080)
register.html
{% from "_formhelpers.html" import render_field %}
<form method=post action="/register">
<dl>
{{ render_field(form.username) }}
{{ render_field(form.email) }}
{{ render_field(form.password) }}
{{ render_field(form.confirm) }}
{{ render_field(form.accept_tos) }}
</dl>
<p><input type=submit value=Register>
</form>
_formhelpers.html
{% macro render_field(field) %}
<dt>{{ field.label }}
<dd>{{ field(**kwargs)|safe }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
表单程序处理见register函数
http://flask.pocoo.org/docs/0.11/patterns/wtforms/
http://blog.csdn.net/zhu_free/article/details/45953325
http://blog.csdn.net/aotony_1988/article/details/40615149