前情提要:
如果你使用google,搜索关键字“flask的endpoint”,前五个链接中,一个是英文的,另外四个是中文的,而后者无不是前者的翻译版本。但由于英文原版的答案已经有6年的历史了,所以如果你想尝试,里面的例子其实是根本运行不出来的。
这是我写这篇的原因。
个人理解:
如果把答案中的例子稍作修改:
第一个例子
@app.route('/') def index(): return redirect(url_for('cesuo', name='shit')) @app.route('/cesuo/<name>') def wc(name): return 'Hello, {0}!'.format(name)
你进入界面,然后使用url_for函数,redirect一个叫做“cesuo/shit”的地方,尝试运行,会报错。
如何正确?两个方法,
第一个方法(第二个例子):
把wc函数,改称中文拼音,cesuo。
@app.route('/') def index(): return redirect(url_for('cesuo', name='shit')) @app.route('/cesuo/<name>') def cesuo(name): return 'Hello, {0}!'.format(name)
第二个方法(第三个例子):
把url_for的参数,改称wc。
@app.route('/') def index(): return redirect(url_for('wc', name='shit')) @app.route('/cesuo/<name>') def wc(name): return 'Hello, {0}!'.format(name)
由此,我们能够推断,使用url_for拼接,然后再redirect,会直接奔着函数的名字走(cesuo对cesuo,wc对wc),名字不一样,就找不到位置。
这时,我们可以在第一个例子的wc函数装饰处,加入endpoint=“cesuo”,即:
@app.route('/') def index(): return redirect(url_for('cesuo', name='shit')) @app.route('/cesuo/<name>',endpoint="cesuo") def wc(name): return 'Hello, {0}!'.format(name)
这意味着,url_for的参数,其实是找endpoint的,默认是目标view function的函数名,如果找不到,就报错,如果加入endpoint参数,即使你的route地址和函数名瞎改,也能找到厕所,例如:
@app.route('/') def index(): return redirect(url_for('cesuo', name='shit')) @app.route('/what_are_you_doing/<name>',endpoint="cesuo") def wc(name): return 'Hello, {0}!'.format(name)
原文地址:https://www.cnblogs.com/kykai/p/13456233.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。