import os
from flask import (
Flask,
render_template,
session,
redirect,
url_for,
flash
)
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from flask_sqlalchemy import SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(basedir, 'data.sqlite') #增加這一行
class NameForm(FlaskForm):
name = StringField('what is your name?', validators=[DataRequired()])
submit = SubmitField('submit')
app = Flask(__name__)
bootstrap = Bootstrap(app)
app.config['SECRET_KEY'] = 'head to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+filepath #修改這行
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
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 f'<Role {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 f'<User {self.username}>'
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username=form.name.data)
db.session.add(user)
db.session.commit()
session['known'] = False
else:
session['known'] = True
session['name'] = form.name.data
form.name.data = ''
return redirect(url_for('index'))
return render_template(
'index.html',
form=form,
name=session.get('name'),
known=session.get('known', False)
)
@app.errorhandler(404)
def page_notfound(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
if __name__ == "__main__":
app.run(debug=True)
以上是我照著"flask網頁開發"這本數打的程式碼
到第五章要用"flask shell"操作資料庫插入資料列卻一直報錯
以下是錯誤資訊
在flask shell執行的是
from hello import Role, User 此行正常執行
admin_role =Role(name="Admin") 此行報錯
卡很久拜託各位幫幫忙!!!
解決這問題!
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: users.role_id
[SQL: SELECT users.id AS users_id, users.username AS users_username, users.role_id AS users_role_id
FROM users
WHERE users.username = ?
LIMIT ? OFFSET ?]
[parameters: ('llllll', 1, 0)]
(Background on this error at: http://sqlalche.me/e/e3q8)
已解決
大概是路徑問題
上面程式碼也有標註修改點
你有用create_all()
把資料庫建立起來嗎?