我在 Flask 应用程序中遇到运行时错误,我正在寻求帮助来解决该问题。我的 Python 文件名为“auth.py”,附近有一个“database.db”文件。
这是我面临的错误消息:
File "<stdin>", line 1, in <module>
File "path\to\auth.py", line 10, in <module>
db = SQLAlchemy(app)
...
RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.
from flask import Flask, render_template, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Length, ValidationError
from flask_bcrypt import Bcrypt
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SECRET_KEY'] = 'thisisasecretkey'
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
@app.route('/')
def home():
return render_template('base.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
return render_template('login.html')
@ app.route('/register', methods=['GET', 'POST'])
def register():
return render_template('register.html')
if __name__ == "__main__":
app.run(debug=True)
我已确认“database.db”文件与“auth.py”位于同一目录中。是什么导致了这个运行时错误,我该如何解决它?
任何帮助或指导将不胜感激。
谢谢!
你应该添加
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SECRET_KEY'] = 'thisisasecretkey'
在
db = SQLAlchemy(app)
之前。
在设置 DB_PARAMS(例如
SQLALCHEMY_DATABASE_URI
)之前,不应启动数据库。这是因为 SQLAlchemy(app)
加载了所有配置变量。
在您的情况下,您正在初始化
db = SQLAlchemy(app)
,它尝试加载 SQLALCHEMY_DATABASE_URI
(尚未设置),因此您会看到错误。
更新代码:
from flask import Flask, render_template, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Length, ValidationError
from flask_bcrypt import Bcrypt
app = Flask(__name__)
app.config['SECRET_KEY'] = 'thisisasecretkey' # also move secret key to top.
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
# move here
db = SQLAlchemy(app)
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
@app.route('/')
def home():
return render_template('base.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
return render_template('login.html')
@ app.route('/register', methods=['GET', 'POST'])
def register():
return render_template('register.html')
if __name__ == "__main__":
app.run(debug=True)