使用SQL Alchemy在Flask应用程序中不会发生数据库输入?

时间:2015-01-16 16:05:59

标签: python flask flask-sqlalchemy

APP CODE :数据库中没有条目,我是Flask的新手,我无法连接到数据库并进入它,我感到困惑的是我的代码完全没有右

from flask import *
from wtforms import *
from wtforms.validators import Required
from flask.ext.wtf import Form
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.secret_key = 'MY CSI FORM'

branch_choices = [('CSE','CSE'),('ECE','ECE'),('MEC','MEC'),('CIVIL','CIVIL')]
year_choices = [('1st','1st'),('2nd','2nd'),('3rd','3rd'),('4th','4th')]
cmem_choices = [('Yes','Yes'),('No','No')]

class CSIForm(Form):
    er = IntegerField('Enrollment No',validators=[Required()])
    name = StringField('Name', validators=[Required()])
    branch = SelectField('Branch',choices=branch_choices, validators=[Required()])
    year = SelectField('Year',choices=year_choices, validators=[Required()])
    cmem = SelectField('CSI Member',choices=cmem_choices,validators=[Required()])
    sop = TextAreaField('Statement of Purpose', validators=[Required()])
    submit = SubmitField('Submit')

数据库代码:SQLAlchemy中的数据库创建代码不知道它是否正确

db = SQLAlchemy(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

class CSI(db.Model):
    __tablename__ = 'form'

    er = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    branch = db.Column(db.String(3))
    year = db.Column(db.String(3))
    cmem = db.Column(db.String(3))
    sop = db.Column(db.String(50))

    def __init__(self, er, name, branch, year, cmem, sop):
        self.er = er
        self.name = name
        self.branch = branch
        self.year = year
        self.cmem = cmem
        self.sop = sop

def connect_db():
    db.create_all()

应用程序运行和连接

@app.route('/', methods=['GET', 'POST'])
def index():
    form=CSIForm(request.form)
    connect_db()
    if form.validate_on_submit():
        csi = CSI()
        form.populate_obj(csi)
        flash('Thanks for registering')
    return render_template('form.html',form=form)

if __name__ == "__main__":
    app.debug='True'
    app.run()

1 个答案:

答案 0 :(得分:1)

您可能希望阅读sessions in SQLAlchemy。您需要将csi添加到当前会话并提交事务。

def index():
    form = CSIForm(request.form)
    connect_db()
    if form.validate_on_submit():
        csi = CSI()
        form.populate_obj(csi)

        # These lines are new.
        db.session.add(csi)
        db.session.commit()

        flash('Thanks for registering')