flask路由和视图函数的问题

查看:210
本文介绍了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 %}

解决方案

关于这个问题,详细的介绍说明可以参考 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 ?』,有可能完全是个人喜好,也可能是作者故意设计成这样,让你提问、思考、实践。

这篇关于flask路由和视图函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆