flask表单提交和数据库的交互

flask表单

  1. 初始化表单
    from wtforms import StringField,SubmitField,validators
    from flask_wtf import Form
  2. 创建表单类
    class formname(Form):
    pass

例如:
string=StringField(u'请输入文字:',validators=[Required()])
submit=SubmitField('Submit')

  1. 渲染表单
    • 方式一:
      from flask import request
      {% import "wtf.html" as wtf %}
      {{wtf.quick_form(form)}}
    • 方式二:
      {{form.string.label}}{{form.string()}}
  2. 接收表单数据
  • 方式一:
    try:
    string=request.form['string']
    except KeyError as err:
    pass
    finally:
    pass
  • 方式二:
    form.string.data

flask-sqlalchemy数据库框架使用

  1. 初始化数据库链接
    from flask_sqlalchemy import SQLAlchemy
    app.config['SQLALCHEMY_DATABASE_URI'] =''
    db = SQLAlchemy(app)
  2. 操作
    增:db.session.add()
    删:db.session.delete()
    查:test.query.filter_by(条件)
    改:
    data=test.query.filter_by(string='hell world!').first()
    data.string='hello world'
    db.session.add(data)
    db.session.commit()
  3. wtforms字段和检验函数
IMG_20161211_143243.jpg

你可能感兴趣的:(flask表单提交和数据库的交互)