我可以在Flask和SQLAlchemy中避免循环导入 [英] Can I avoid circular imports in Flask and SQLAlchemy

查看:227
本文介绍了我可以在Flask和SQLAlchemy中避免循环导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

app/ init .py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__ name __)
db = SQLAlchemy(app)  
from app import views, models

app/models.py:

app/models.py:

from app import db  # I want to avoid this everywhere

我真的不喜欢子模块依赖于其父模块.也可以避免全局包变量吗?我想要更多面向对象的解决方案.

I really don't like my submodules having a dependency on their parent. Also can the global package variables be avoided too? I want a more OO solution.

应用程序的一种替代方法是使用我认为的蓝图,但是随后我松开了路线装饰器.同样,对于使用SQLAlchemy的数据库也无法做到这一点(或者可以吗?).

One alternative for app is to use Blueprints I think, but then I loose the route decorator. Also the same cannot be done for db with SQLAlchemy (or can it?).

推荐答案

看一下这个项目: https ://github.com/sloria/cookiecutter-flask
这是以正确的方式做事的一个很好的例子.使用了许多Flask的出色功能:蓝图,应用程序工厂等.

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

这篇关于我可以在Flask和SQLAlchemy中避免循环导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆