初学 flask,问个问题,绕了半天了。。

2017-07-04 00:09:47 +08:00
 Tianny

先上代码,这个是 routing 和 view

@auth.route('/change-password', methods=['GET', 'POST'])
@login_required
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.old_password.data):
            current_user.password = form.password.data
            db.session.add(current_user)
            flash('Your password has been updated.')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid password.')
    return render_template("auth/change_password.html", form=form)

这个是 change_password.html 的模板文件

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Flasky - Change Password{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Change Your Password</h1>
</div>
<div class="col-md-4">
    {{ wtf.quick_form(form) }}
</div>
{% endblock %}%

这个是各个模板的父模板 base.html 中的相关部分

<li><a href="{{ url_for('auth.change_password') }}">Change Password</a></li>

上面实现的功能是,已登录用户如果点击 Change Password,链接就会跳转到 /change-password,跳出一个重置密码的表单,点完提交按钮后,application 然后再执行对应的 view function。

我的问题是:当点击 Change Password 后,跳转到 /change-password 地址后,会展现一个重置密码的表单,我没理解的地方是,按照路由映射关系,/change-password 这个 url 交由 change_password()这个视图处理,按照函数执行的顺序,先引用表单即 form=ChangePasswordForm(),然后更新密码,最后返回一个重定向到主页,就结束了。这样的话,那么return render_template("auth/change_password.html", form=form)这段代码压根就没执行到,都没有返回渲染后的模板文件,又怎么有了前面点击 chang password 就蹦出一个重置密码表单的页面呢?

这里我给绕晕了,求解释下,谢谢大家

2192 次点击
所在节点    Python
10 条回复
coolair
2017-07-04 00:22:52 +08:00
点了 submit 才会重定向到 index,没点就显示这个页面,注意有个 if。
troywinter
2017-07-04 00:23:35 +08:00
你点击 chang_password 时是一个 get 请求,所以 if 那块的代码根本不会执行,执行的只是 render_template 那块的代码,想看到底执行没执行打个断点看看,就明白了
welkinzh
2017-07-04 00:50:35 +08:00
点击 submit 后才会跳转到 index 不然渲染的是 change passwd 页面呀
kimchan
2017-07-04 09:41:07 +08:00
if form.validate_on_submit()
Tianny
2017-07-04 10:32:24 +08:00
@coolair 感谢
Tianny
2017-07-04 10:32:44 +08:00
@troywinter 厉害了 一阵见血
Tianny
2017-07-04 10:32:54 +08:00
@kimchan thx
Tianny
2017-07-04 10:33:07 +08:00
xvx
2017-07-04 16:59:49 +08:00
GET 请求和 POST 请求,执行的是不同的代码。打开的时候是 GET 请求,返回的是 change_password.html 页面,点击提交的时候是 POST 请求,才会执行 validate_on_submit()后面的代码。
Tianny
2017-07-04 18:56:53 +08:00
@xvx 恩 知道了 thx !

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/372806

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX