新手求助:
在视图文件中创建db.model类,运行正常
把模型分离出来,报错:
RuntimeError: The current Flask app is not registered with this ‘SQLAlchemy’ instance. Did you forget to call ‘init_app’, or did you create multiple ‘SQLAlchemy’ instances?
正常运行的代码如下:
【app.py】
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = r"mysql+pymysql://username:password@127.0.0.1:3306/mydb"
db = SQLAlchemy(app)
from datetime import datetime
class Category(db.Model):
__tablename__ = "category"
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment="自增主键ID")
name = db.Column(db.String(20), default=None, nullable=False, comment="类别名称")
def __init__(self, items):
Super().__init__()
for key in items:
if hasattr(self, key):
setattr(self, key, items[key])
def __repr__(self):
return r"类别ID:{id} 名称:{name}".format(
id=self.id,
name=self.name
)
@app.route('/hello', methods=['get', 'post'])
def home():
obj = Category.query.first()
return str(obj)
if __name__ == '__main__':
app.run(host="127.0.0.1", port="8008", debug=True)
报错的、分成2个文件的代码如下:
【文件1:app.py】
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = r"mysql+pymysql://username:password@127.0.0.1:3306/mydb"
db = SQLAlchemy(app)
@app.route('/hello', methods=['get', 'post'])
def home():
from model import Category
obj = Category.query.first()
return str(obj)
if __name__ == '__main__':
app.run(host="127.0.0.1", port="8008", debug=True)
【文件2:model.py】
from datetime import datetime
from app import db
class Category(db.Model):
__tablename__ = "category"
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment="自增主键ID")
name = db.Column(db.String(20), default=None, nullable=False, comment="类别名称")
def __init__(self, items):
Super().__init__()
for key in items:
if hasattr(self, key):
setattr(self, key, items[key])
def __repr__(self):
return r"类别ID:{id} 名称:{name}".format(
id=self.id,
name=self.name
)
被这个问题堵了几个小时,网上也没查出啥,求助,万分感激!