在蓝图中使用url_for [英] Using url_for across blueprints
问题描述
url_for
是否可以在蓝图上工作? / flaskapp
/runserver.py(from server import app; app.run(debug = True))
/ server
/__init__.py(app = Flask(__ name__))
/ pages
/__init__.py('pages'blueprint)
/ users
/__init__.py('users'blueprint)
在 server / __ init __。py
:
server.puse中的从server.users导入用户
导入用户
app = Flask(__ name__)
app.register_blueprint(pages)
app.register_blueprint(users)
位于 server / pages / __init __。py
:
pages =蓝图('pages',__name__)
@ pages.route('/')
def index():return'< h1>索引< / h1>'
位于 (我试过导入模块,但是没有成功) < h1>短的答案:是的 尽我所能, 我已经重新创建了您的设置(虽然在一个文件中),您可以在这里结帐。此代码在我的计算机上运行。 server / users / __ init __。py
:
<$ p $ ($ / $登录)
def登录():
。用户=蓝图('users',__name__)
@ users.route ..
return redirect(url_for('pages.index'))
^^^^^^^^^^^^^^^^^^^^^^
$ b url_for
调用引发 BuildError: pages.index',{},None)
什么是到达'pages.index'
?
长(ish)答案:
在烧瓶中,您可以使用相对终端( (
user.login
)。
在所有的蓝图中,或者通过绝对的(
user.login
我的钱是在你有一个错误的视图函数名称。
像马克·希尔德雷斯在评论中说,一个很好的方式来调试问题是要看看你的网址。
>>> from app import app
>>> app.url_map $ b $ Map([< Rule'/ login'(HEAD,OPTIONS,GET) - > user.login> ;,
< Rule'/'(HEAD,OPTIONS,GET) > pages.index> ;,
< Rule'/ static /< filename>'(HEAD,OPTIONS,GET) - > static>])
>>>
Does url_for
work across blueprints?
/flaskapp
/runserver.py (from server import app; app.run(debug=True))
/server
/__init__.py (app = Flask(__name__))
/pages
/__init__.py ('pages' blueprint)
/users
/__init__.py ('users' blueprint)
in server/__init__.py
:
from server.pages import pages
from server.users import users
app = Flask(__name__)
app.register_blueprint(pages)
app.register_blueprint(users)
in server/pages/__init__.py
:
pages = Blueprint('pages', __name__)
@pages.route('/')
def index(): return '<h1>Index</h1>'
in server/users/__init__.py
:
users = Blueprint('users', __name__)
@users.route('/login')
def login():
...
return redirect(url_for('pages.index'))
^^^^^^^^^^^^^^^^^^^^^^
The url_for
call raises BuildError: ('pages.index', {}, None)
What would be a way to get to 'pages.index'
?
(I tried importing the module, but that didn't work)
Short Answer: Yes
Long(ish) Answer:
As best I can tell, you're organizing your app the way you should.
I've recreated your setup (albeit in a single file), which you can checkout here. This code runs on my machine.
https://gist.github.com/enlore/80bf02346d6cabcba5b1
In flask, you can access a given view function with a relative endpoint (.login
) from within the owning blueprint, or an via an absolute one (user.login
) anywhere.
My money is on you having a typo in a view function name.
Like Mark Hildreth said in the comments, a great way to debug your problem would be to take a look at your url map.
>>> from app import app
>>> app.url_map
Map([<Rule '/login' (HEAD, OPTIONS, GET) -> user.login>,
<Rule '/' (HEAD, OPTIONS, GET) -> pages.index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>])
>>>
这篇关于在蓝图中使用url_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!