开发者社区> 问答> 正文

flask db.session.commit()抛出 InvalidRequestError?

在python中运行db.session.commit()抛出

`Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\wtf\myenv\lib\site-packages\sqlalchemy\orm\scoping.py", line 157, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "C:\Users\wtf\myenv\lib\site-packages\sqlalchemy\orm\session.py", line 801, in commit
    self.transaction.commit()
  File "C:\Users\wtf\myenv\lib\site-packages\sqlalchemy\orm\session.py", line 390, in commit
    self._assert_active(prepared_ok=True)
  File "C:\Users\wtf\myenv\lib\site-packages\sqlalchemy\orm\session.py", line 214, in _assert_active
    % self._rollback_exception
InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.OperationalError) table users has no column named role_id [SQL: u'INSERT INTO users (username, role_id) VALUES (?, ?)'] [parameters: ('join', 1)]`
xuanran.py

from flask import Flask, render_template, session, redirect,url_for, flash
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from datetime import datetime
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask.ext.sqlalchemy import SQLAlchemy
import os


basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = \
    "sqlite:///" + os.path.join(basedir, "data.sqlite")
app.config["SQLALCHEMY_COMMIT_ON_TEARDOWN"] = True
db = SQLAlchemy(app)
app.config["SECRET_KEY"] = "hard to guess string"
manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
now = datetime.now()

class NameForm(Form):
    name = StringField("What is your name ?", validators = [Required()])
    submit = SubmitField("Submit")
class Role(db.Model):
    __tablename__ = "roles"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship('User', backref='role')
    def __repr__(self):
        return "<Role %r>" % self.name
class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    def __repr__(self):
            return "user %r" % self.username
            
@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get("name")
        if old_name is not None and old_name != form.name.data:
            flash ("Looks like you have changed your name !")
        session["name"] = form.name.data
        return redirect(url_for("index"))
    return render_template('index.html', form=form, name=session.get('name'))    
    
@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)
    manager.run()

求教!

展开
收起
a123456678 2016-07-04 15:20:28 4065 0
1 条回答
写回答
取消 提交回答
  • users表中的role_id项是后加上去的吧?需要用migrate做个数据库迁移才可以。

    2019-07-17 19:50:43
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载