Can I avoid circular imports in Flask and SQLAlchemy

ⅰ亾dé卋堺 提交于 2019-11-28 05:59:28

Take a look at this project: https://github.com/sloria/cookiecutter-flask
It's a great example for doing things the right way. Many of great Flask features are used: blueprints, application factories and more.

Here is how they register extensions, such as SQLAlchemy Database:

# app/extensions.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...


# app/app.py
from app.extensions import db

def create_app(config_object=ProdConfig):
    app = Flask(__name__.split('.')[0])
    app.config.from_object(config_object)
    register_extensions(app)
    ...

def register_extensions(app):
    db.init_app(app)
    ...

Try use 3rd. We create exts.py file to instancing SQLAlchemy like this:

exts.py

from flask_sqlalchemy import SQLAlchemy
from flask_xxx import xxx

db = SQLAlchemy()
...

run.py

from flask import Flask

from .exts import db, ...


def register_extensions(app):
    db.init_app(app) 
    ... 


def create_app(config):
    app = Flask(__ name __)
    app.config.from_object(config)

    register_extensions(app)

    return app

app = create_app(config)

models.py

from .exts import db


class XXXModel(db.Model):
    pass    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!