基于python flask框架搭建web
flask后台与前端(html)交互的两种方法:
方法1 使用flask-wtf 提供的表单
用常见的登录为例:
// An highlighted block
from flask_wtf import Form
class LoginForm(Form): # 登录表单
ROLE = SelectField('角色', choices=[('s', '管理员'), ('n', '用户')], render_kw={"placeholder": "输入你的用户名", "sty"
"le": "background:url(/static/user."
"png) no-repeat 15px center;t"
"ext-indent: 28px"})
email = StringField('', validators=[Required(), Length(1, 64),
Email()], render_kw={"placeholder": "请输入邮箱",
"style": "background:url(/static/email"
".png) no-repeat 15px center;"
"text-indent: 28px"})
password = PasswordField('', validators=[Required()], render_kw={"placeholder": "输入你的密码", "style": "back"
"ground:url(/static/password.pn"
"g) no-repeat 15px center;text-"
"indent: 28px"})
verify_code = StringField('', validators=[Required()], render_kw={"placeholder": "验证码", "style": "back"
"ground:url(/static/password.pn"
"g) no-repeat 15px center;text-"
"indent: 28px"})
remember_me = BooleanField('记住密码')
submit = SubmitField('登录')
视图函数定义的路由(后台处理程序):
@auth.route('/login', methods=['GET', 'POST']) # 登陆路由
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if session.get('image').lower()!=form.verify_code.data.lower():
flash('验证码错误')
return render_template('auth/login.html', form=form)
if user is not None and user.verify_password(form.password.data) and (user.ROLE == form.ROLE.data): # user.ROLE == form.ROLE.data:
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('main.index'))
flash('邮箱或者密码错误,请检查后再试.')
return render_template('auth/login.html', form=form)
与html模板:
// An highlighted block
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky - Login{% endblock %}
{% block page_content %}
登录
{{ wtf.quick_form(form) }}
{% endblock %}
结果如图:
方法2 直接使用HTML中的form
html代码如下:Purple_loginform Website Template | Home :: w3layouts
Login Form