python - 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
解决方案
推荐阅读
- laravel - 尝试使用 laravel 获取非对象的属性“id”
- github - Hackerrank - 有没有办法一次下载我所有的提交?
- matlab - 为什么插值给我 NANi 值
- algorithm - 表达式的时间复杂度
- typescript - 将打字稿中的多种类型声明为字符串和数组
- xamarin - Xamarin - 不能使用 iOS 模拟器?
- python - Kivy.uix.images 不工作仅返回空白屏幕
- java - 我想在 ACTION_CALL 的帮助下按下我的移动应用程序中的按钮来拨打紧急号码,但我没有。为什么?
- c - 在 c 中的特定字母处拆分用户输入的字符串
- python - .txt.File 中带有 Selenium 的安全 dublets