flask db.session.commit()抛出 InvalidRequestError?-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

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

a123456678 2016-06-29 11:05:25 2010

在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()

求教!

SQL 前端开发 数据库管理 Python 内存技术
分享到
取消 提交回答
全部回答(1)
  • a123456678
    2019-07-17 19:48:54

    users表中的role_id项是后加上去的吧?需要用migrate做个数据库迁移才可以。

    0 0
数据库
使用钉钉扫一扫加入圈子
+ 订阅

分享数据库前沿,解构实战干货,推动数据库技术变革

推荐文章
相似问题
推荐课程