首页 > 解决方案 > Flask 在无法找到变量时抛出 AttributeError,尽管它在那里

问题描述

我遇到了一点问题,Flask 似乎认为bp这些蓝图类中没有属性,它添加了蓝图路由,但仍然记录了一个错误,这让我很难受。

app.py 导入代码

for dirpath, dirnames, filenames in os.walk('blueprint'):

    for filename in filenames:
        if filename.endswith(".py"):
            fullpath = os.path.join(dirpath, filename).split(os.sep)
            module = ".".join(fullpath)[:-3]

            try:
                module = importlib.import_module(module)
                prefix = module.__name__.split('.')[-1:][0]
                if prefix.startswith('_'):
                    app.register_blueprint(module.bp)
                else:
                    app.register_blueprint(
                        module.bp, url_prefix=f'/{prefix}')
            except Exception as error:
                print(f"{type(error)} Unable to load {module}: {error}")

示例蓝图(即 index.py)

bp = Blueprint('', __name__)

@bp.route('/')
def index(*args, **kw):

    return render_template('index.html')

输出

<class 'AttributeError'> Unable to load <module 'blueprint._index' from '~~~/blueprint/_index.py'>: module 'blueprint._index' has no attribute 'bp'

正如您所看到的,bp变量在那里,并且添加了路由,但是没有try/except添加路由..它相当烦人,我宁愿不只是pass它们..

编辑

目录树

  - app.py
  - blueprints/
      - index.py
      - etc.py

标签: pythonflaskpython-3.6

解决方案


推荐阅读