如何使用Flask将POST传递到另一个URL [英] How to pass your POST to another URL using Flask

查看:72
本文介绍了如何使用Flask将POST传递到另一个URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从用户那里获取一些短语,当他/她按下提交"时,我想使用Flask将他/她重定向到具有他/她名字的另一个页面.这是我的Python代码:

I am trying to get some phrase from the user, and when he/she will press "submit" i want to redirect him/her to another page with his/her name, using Flask. Here is my Python code:

from flask import Flask, redirect, render_template, request, session, url_for

app = Flask(__name__)

@app.route("/", methods = ["POST", "GET"])
def login():
    if request.method == "POST":
        user = request.form["name"]
        return redirect(url_for("success", name=user))
    else:
        return render_template("login.html")

@app.route("/success", methods = ["POST", "GET"])
def success():
    user = request.form.get('name')
    return render_template("success.html", name=user)

if __name__ == "__main__":
    app.run("0.0.0.0", 8080)

因此,当我转到自己的网站时,我将转到"else"分支并执行:"render_template("login.html")".然后,如果我按提交,我进入如果",我试图将用户重定向到"success.html".这是我的login.html:

So when i go to my site i am going to "else" branch and do: "render_template("login.html")". Then if i press submit i go into "if" where i am trying to redirect the user to "success.html". Here is my login.html:

<html>
   <body>

      <form action = "http://ide50-zahar-zagrava.cs50.io:8080/" method = "post">
         <p>Enter Name:</p>
         <p><input type = "text" name = "name" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>

   </body>
</html>

和succes.html:

And succes.html:

<html>
    <body>
        <h1>Hello {{ name }}!</h1>
    </body>
</html>

但是有话要说:你好",它说:你好,没有".我的主要问题是如何将数据从一页传递到另一页?我对Flask和Python完全陌生,所以我不知道出了什么问题.

But insted of saying: "Hello " it says: "Hello None". My main question is how to pass data from one page to another? I am completely new at Flask and Python, so i can't figure out what's going wrong.

推荐答案

form 中的 action 错误.您正在将表单发送到索引页面.您可以像这样编辑它:

your action from form is wrong.you are sending the form to the index page. you could edit it like:

<form action="{{ url_for('success') }}" method="post">

这样,您的表格将被发送到成功方法.

this way, your form will be sent to the success method.

这篇关于如何使用Flask将POST传递到另一个URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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