我正在使用 Flask 制作一个网络应用程序,并且需要使用两个或更多数据库。我阅读了有关它的文档,但出现错误。
这是我的代码:
path = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secretkey'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(path, 'databaseteste.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_BINDS'] = {
'user_database': 'mysql:///root:password@localhost/userdatabase'
}
db = SQLAlchemy(app)
# User model to database
class User(UserMixin, db.Model):
__bind_key__ = 'user_database'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), unique = True, index = True)
password_hash = db.Column(db.String(128))
joined_at = db.Column(db.DateTime(), default = datetime.utcnow, index = True)
def __repr__(self):
return f'User {self.username}'
def set_passoword(self, password):
self.password_hash = generate_password_hash(password)
...
当我尝试运行该应用程序时,出现此错误:
ModuleNotFoundError:没有名为“MySQLdb”的模块
我在代码中发现了问题。
我在文档中粘贴了默认路径,但忘记更改。
...
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_BINDS'] = {
'user_database': 'sqlite:///' + os.path.join(path, 'user-database.db')
}
...
刚刚更改为:
'sqlite:///' + os.path.join(path, 'user-database.db')