使用app factory flask时,在单独的文件中定义模型
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用app factory flask时,在单独的文件中定义模型相关的知识,希望对你有一定的参考价值。
我正在创建一个烧瓶应用程序,我正在使用app工厂方法。我在应用程序文件夹__init__.py
中有一个文件,它有create_app
函数,代码如下
def create_app(test_config=None):
app = Flask(__name__,instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:@localhost/database'
db = SQLAlchemy(app)
if test_config == None:
app.config.from_pyfile('config.py',silent=True)
else:
app.config.form_mapping(test_config)
from flaskr import models
try:
os.makedirs(app.instance_path)
except OSError:
pass
class User(db.Model):
id = db.Column(db.Integer,primary_key=True)
uname = db.Column(db.String(50))
@app.route('/hello')
def hello():
return json.dumps({'message':'hello','status':True})
@app.route('/getusers')
def getusers():
u = User.query.get(1)
return json.dumps({'uname':u.uname})
return app
我想要的是在一个单独的文件中定义模型。我怎样才能做到这一点?我尝试在单独的文件中定义并导入它。但问题是模型继承了db.Model
,然后在导入的文件中不可用。
答案
将db
对象的创建保留在create_app
之外,而不传递任何app
实例,并使用SQLAlchemy.init_app
方法进行配置和初始化。你的db
对象,这样你可以从任何文件import
它:
db = SQLAlchemy()
#...
def create_app(test_config=None):
app = Flask(__name__,instance_relative_config=True)
#...
db.init_app(app)
有关此主题的更多信息,请访问flask's documentation
以上是关于使用app factory flask时,在单独的文件中定义模型的主要内容,如果未能解决你的问题,请参考以下文章
使用 Google App Engine 时无法导入 Flask
与 Google App Engine 和 Flask 一起使用时,Angular 路由不起作用