简体   繁体   中英

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) . 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.

Models should import db from database and the app should just import the models.

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:

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:

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.

To use I then import the db from the extensions file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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