推荐学习书目
› 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
PanameraM
V2EX  ›  Python

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

  •  
  •   PanameraM · Jun 28, 2017 · 2190 views
    This topic created in 3441 days ago, the information mentioned may be changed or developed.
    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 replies  •  2017-06-28 10:37:06 +08:00
    guyskk
    guyskk
    Jun 28, 2017 via Android❤️1
    1
    main_blueprint 很可能依赖 db,把这个 import 放到顶上会造成循环依赖,import 会失败。放到 db = xxx 这行下面应该没问题。
    PanameraM
    PanameraM
    OP
    Jun 28, 2017
    2
    @guyskk 感谢!你的意思我懂了。是我的思维太局限了。也可以这样说,create_app()中里可能会注册多个 blueprint。而每个 blueprint 都可能依赖 db,mail 等各种扩展实例,所以放在 create_app()函数中 import blueprint 是最稳妥的方法,因为在 create_app()函数之前已经导入了各种模块和创建了所需的扩展实例了,也就不会造成循环依赖了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   907 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 19:23 · PVG 03:23 · LAX 11:23 · JFK 14:23
    ♥ Do have faith in what you're doing.