gpt4 book ai didi

python - Flask 蓝图无法导入模块

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:00 26 4
gpt4 key购买 nike

我正在学习 Flask 的蓝图,但我在导入正确的模块时遇到了问题。这是我的设置:

文件夹结构:

- app.py
templates/
nomad/
- __init__.py
- nomad.py

应用.py

from flask import Flask
from nomad.nomad import nblueprint

app = Flask(__name__)
app.register_blueprint(nblueprint)

游牧民族

from flask import render_template, Blueprint, abort
from app import app

nblueprint = Blueprint('nblueprint', __name__, template_folder='templates')

# Routes for this blueprint
@app.route ....

__init__.py 为空

我收到的错误:ImportError: cannot import name nblueprint。我知道我的导入语句可能是错误的,但它应该是什么以及为什么?

编辑:

如果我删除 from app import app,那么我可以在 app.py 中成功导入 nblueprint。但是我需要在 nomad.py 中使用 app 因为它需要处理路由。为什么该行会导致导入问题,我该如何解决这个问题?

最佳答案

蓝图用于定义应用程序路由,因此您无需在同一位置使用应用实例和蓝图来定义路由。

#nomad.py
@nblueprint.route('/')

您收到错误消息是因为您在注册蓝图的同时使用了应用程序实例。因此,正如您所说,当您从应用程序中删除 ... 时,它解决了问题。

推荐的方法是在示例 nomad 包中的 blueprint 包中定义该蓝图的 View ,它应该是这样的:

...
nomad/
__init__.py
views.py
#nomad/__init__.py
nblueprint = Blueprint(...)
#nomad/views.py
from . import nblueprint
@nblueprint.route('/')
...

关于python - Flask 蓝图无法导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com