简体   繁体   English

正确初始化SQLAlchemy的方法

[英]Right way for initializing SQLAlchemy

Many tutorials say to create an application with Flask(__name__) and from there we can initialize the database with SQLAlchemy(app) . 许多教程都说使用Flask(__name__)创建一个应用程序,然后我们可以用SQLAlchemy(app)初始化数据库。 However, I don't like this intrusive model, as the application itself doesn't need to know anything about the database. 但是,我不喜欢这种侵入式模型,因为应用程序本身不需要了解有关数据库的任何信息。

I think a better approach would be creating a module called database and initialize the database there. 我认为更好的方法是创建一个名为database的模块并在那里初始化数据库。

Models should import db from database and the app should just import the models. 模型应该import db from database ,应用程序应该只导入模型。

However, with this approach the database module must retrieve the global app by somehow, something which I disagree. 但是,使用这种方法,数据库模块必须以某种方式检索全局应用程序,这是我不同意的。

Is there a property way to initialize the database without importing the main app? 有没有一种属性方法来初始化数据库而不导入主应用程序?

This is the neatest way i have found to set up the flask app: 这是我找到设置烧瓶应用程序的最好方法:
In app.py: 在app.py中:

from flask import Flask
from app.settings import DevConfig
from app.extensions import api, mysqldb, marsh, mongodb 

def create_app(config=DevConfig):
    """Application factory. This is used to run the app from the root.

    :param config: Object to configure app stored in settings.py
    """
    app = Flask(__name__.split('.')[0])
    app.config.from_object(config)
    register_endpoints()
    register_extensions(app)  
    return app

def register_extensions(app):
    """Registration of flask components."""
    mysqldb.init_app(app)
    marsh.init_app(app)
    mongodb.init_app(app)
    api.init_app(app)


Then in extensions.py i'd have something like this: 然后在extensions.py我有这样的事情:

from flask_restful import Api
from flask_httpauth import HTTPBasicAuth
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_pymongo import PyMongo

mysqldb = SQLAlchemy()
mongodb = PyMongo()
marsh = Marshmallow()
api = Api(prefix='/v1')
auth = HTTPBasicAuth()

That way i have things seperate. 那样我就把事情分开了。 There might be a way to loop the init_app in the extensions but then it would be less clean in my opinion. 可能有一种方法可以在扩展中循环init_app但是在我看来它会更不干净。

To use I then import the db from the extensions file. 要使用我,然后从扩展文件导入数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM