flask路由和视图函数的问题

新手上路,请多包涵

flask web开发第八章,路由装饰器route()的参数是/confirm,而视图函数名为resend_confirmation,模板中url_for()的参数为auth.resend_confirmation。请问route()中为什么不是/resend_confirmation ?


@auth.route('/confirm')
@login_required
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    send_email(current_user.email, 'Confirm Your Account',
               'auth/email/confirm', user=current_user, token=token)
    flash('A new confirmation email has been sent to you by email.')
    return redirect(url_for('main.index'))

{% extends "base.html" %}

{% block title %}Flasky - Confirm your account{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>
        Hello, {{ current_user.username }}!
    </h1>
    <h3>You have not confirmed your account yet.</h3>
    <p>
        Before you can access this site you need to confirm your account.
        Check your inbox, you should have received an email with a confirmation link.
    </p>
    <p>
        Need another confirmation email?
        <a href="{{ url_for('auth.resend_confirmation') }}">Click here</a>
    </p>
</div>
{% endblock %}
阅读 3.3k
1 个回答

关于这个问题,详细的介绍说明可以参考 Flask里endpoint view function 路由等概念如何理解 - shajiquan的回答 - SegmentFault https://segmentfault.com/q/10...

简单点说:

  1. endpointflask route 机制中最重要最重要的部分,相当于命名空间,标识符,unique key 之类的,url_for 是使用 endpoint 来定位它的。在您给的示例里,它就是 resend_confirmation,更准确地说,是 auth 这个 blueprint 下的 resend_confirmation

  2. route() 的参数,是一个 path 路径,其实这个路径你可以随便设置N个,同一个 view function、endpoint 可以有 N个路由规则,HTTP 请求时,flask都会把它们定位到这个 route() 下面的那个 view function。

至于说为啥『route()中为什么不是/resend_confirmation ?』,有可能完全是个人喜好,也可能是作者故意设计成这样,让你提问、思考、实践。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进