V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Tianny
V2EX  ›  Python

请教个 flask web development 书中关于 blueprint 注册的问题

  •  
  •   Tianny · 2017-06-28 10:08:34 +08:00 · 1619 次点击
    这是一个创建于 2499 天前的主题,其中的信息可能已经有所发展或是发生改变。
    from flask import Flask
    from flask_bootstrap import Bootstrap
    from flask_mail import Mail
    from flask_moment import Moment
    from flask_sqlalchemy import SQLAlchemy
    from config import config
    
    bootstrap = Bootstrap()
    mail = Mail()
    moment = Moment()
    db = SQLAlchemy()
    
    
    def create_app(config_name):
        app = Flask(__name__)
        app.config.from_object(config[config_name])
        config[config_name].init_app(app)
    
        bootstrap.init_app(app)
        mail.init_app(app)
        moment.init_app(app)
        db.init_app(app)
    
        from .main import main as main_blueprint
        app.register_blueprint(main_blueprint)
    
        return app
    

    上面例子是 flask web development 书中的 7-3 的引用,from .main import main as main_blueprint是在 create_app 中导入已定义的 blueprint,已定义的 blueprint 的名称是 main。我的问题是这段代码可以加到这个例子的最上面么?跟开头的其他 import 语句放在一起,而不是放在 create_app 这个函数中。之所以有这样的疑问,因为书中有提到包的循环导入的问题,放在 create_app 中,是为了解决包循环导入的问题么?

    附加下项目的目录结构

    .
    |______init__.py
    |____email.py
    |____main
    | |______init__.py
    | |____errors.py
    | |____forms.py
    | |____views.py
    |____models.py
    |____static
    | |____favicon.ico
    |____templates
    | |____404.html
    | |____500.html
    | |____base.html
    | |____index.html
    | |____mail
    | | |____new_user.html
    | | |____new_user.txt
    
    2 条回复    2017-06-28 10:37:06 +08:00
    guyskk
        1
    guyskk  
       2017-06-28 10:17:25 +08:00 via Android   ❤️ 1
    main_blueprint 很可能依赖 db,把这个 import 放到顶上会造成循环依赖,import 会失败。放到 db = xxx 这行下面应该没问题。
    Tianny
        2
    Tianny  
    OP
       2017-06-28 10:37:06 +08:00
    @guyskk 感谢!你的意思我懂了。是我的思维太局限了。也可以这样说,create_app()中里可能会注册多个 blueprint。而每个 blueprint 都可能依赖 db,mail 等各种扩展实例,所以放在 create_app()函数中 import blueprint 是最稳妥的方法,因为在 create_app()函数之前已经导入了各种模块和创建了所需的扩展实例了,也就不会造成循环依赖了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1808 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:52 · PVG 08:52 · LAX 17:52 · JFK 20:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.