我可以避免在 Flask 和 SQLAlchemy 中循环导入吗 [英] Can I avoid circular imports in Flask and SQLAlchemy
本文介绍了我可以避免在 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 也不能对 db 做同样的事情(或者可以吗?).
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 功能:蓝图、应用工厂等等.
这里是他们如何注册扩展,例如 SQLAlchemy 数据库:
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屋!
查看全文