V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Hopetree
V2EX  ›  Flask

关于 flask 循环导入的问题?求解释,这个算不算循环导入?

  •  
  •   Hopetree ·
    Hopetree · 2019-03-22 11:46:48 +08:00 · 3202 次点击
    这是一个创建于 1833 天前的主题,其中的信息可能已经有所发展或是发生改变。

    看到一个 flask 项目,结构看的我非常喜欢,所以在学习。但是关于注册蓝图的操作我有点不理解,如下:

    项目结构(部分)

    --app
      --auth
         __init__.py
         views.py
    --run.py
    

    然后我看到auth.__init__.py这样注册蓝图

    from flask import Blueprint
    
    auth = Blueprint('auth', __name__)
    
    from . import views
    

    而在auth.views.py中又引用了 auth

    from . import auth
    
    @auth.route('/unconfirmed')
    def unconfirmed():
        if current_user.is_anonymous or current_user.confirmed:
            return redirect(url_for('main.index'))
        return render_template('auth/unconfirmed.html')
    

    我的理解是这两个文件里面在循环调用 auth 这个蓝图,这样做真的可以吗(当然运行没问题,我问的可以是这样的引用方式是否合理?)

    说说我的做法,我在 views 里面不会引用 auth,而是这是一个函数,传入 auth,然后__init__.py中引入这个函数来注册蓝图

    #__init__.py
    from flask import Blueprint
    from .views import init_blueprint
    
    bp = Blueprint('main', __name__)
    
    
    def init_app(app):
        init_blueprint(bp)
        app.register_blueprint(bp)
    
    #views.py
    from flask import jsonify, current_app
    
    
    def index():
        return ''
    
    
    def init_blueprint(bp):
        bp.add_url_rule('/', 'home', index)
    
    

    我这样做主要是避免循环引入,求解释上面的那个代码算不散循环导入?这 2 个方式最大的区别在于第一种可以使用装饰器,第二种只能使用 add_url_rule 去注册路由

    项目源码: https://github.com/miguelgrinberg/flasky/blob/master/app/auth/views.py

    2 条回复    2019-03-22 12:07:29 +08:00
    GTim
        1
    GTim  
       2019-03-22 12:06:32 +08:00
    当然是不会的啦,因为它们都是到文件级别的,而不是函数变量级别的,不需要即刻扫描

    Python 的 import 机制说复杂也复杂,说简单也简单。最重要的是理解: 在执行 import A 时,会先在 sys.modules 查找,如果找不到则会先创建一个 A 键,然后再填充 A 的具体东西
    fngtz
        2
    fngtz  
       2019-03-22 12:07:29 +08:00 via iPhone
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3499 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:59 · PVG 18:59 · LAX 03:59 · JFK 06:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.