V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ry_wang
V2EX  ›  Flask

flask中如何实现支持template传参的redirect.

  •  
  •   ry_wang ·
    saipanno · 2013-01-19 23:07:07 +08:00 · 12341 次点击
    这是一个创建于 4107 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如当前有两个页面:
    一个创建用户的页面, http://localhost/user/create,对应user_create方法,对应user_create.html模板.
    一个用户列表显示页面, http://localhost/user/show,对应user_show方法,对应user_show.html模板.

    用户创建成功后通过redirect将页面重定向到/user/show这个页面展示所有的用户列表.现在我在页面中显示一个user create successful或fail的message. 但redirect不支持类似render_template这种的传参功能.

    不知各位有啥好的解决办法呢?谢谢.
    下面为这个问题的代码.那个message传不进去参数...

    @app.route('/operate/create', methods=("GET", "POST"))
    def user_create():
    form = UserCreateForm()
    if request.method == 'GET':
    return render_template('user/user_create.html', form=form)
    elif request.method == 'POST':
    user = User(0, form.user.data, form.password.data)
    db.session.add(user)
    db.session.commit()
    return redirect(url_for('user_show', status='success', message='User create successful.'))

    @app.route('/user/show')
    def user_show():
    if request.method == 'GET':
    users = User.query.filter_by(type=0).order_by(desc(User.id)).all()
    return render_template('user_show.html', users=users)
    3 条回复    1970-01-01 08:00:00 +08:00
    lix
        1
    lix  
       2013-01-19 23:15:58 +08:00
    用flash
    linnchord
        2
    linnchord  
       2013-01-19 23:16:49 +08:00   ❤️ 1
    这个……最基础的问题,看清楚文档先……

    如果你确实要传递url参数,请定义好方法参数

    @app.route('/user/show/<message>')
    def user_show(message):

    然后才能
    return redirect(url_for('user_show', message='User create successful.'))

    不过看你上面描述,你只是要显示一个消息,那可以用内置的flash方法

    flask中文文档
    http://docs.torriacg.org/docs/flask/quickstart.html

    哪怕你只看快速入门也可以解答上面问题了
    ry_wang
        3
    ry_wang  
    OP
       2013-01-19 23:46:33 +08:00
    呃,忘掉这块了,谢谢二位..
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5102 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:32 · PVG 17:32 · LAX 02:32 · JFK 05:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.