Flask:为什么 HTML 提交按钮不将页面重定向到目标 URL?

Flask : Why does not the HTML submit button redirect the page to the target URL?

我是 Flask 新手。这是我的 login.html 文件的内容:

<html>
    <body>
        <form action="localhost:5000/login" method="POST">
            <p>Enter name : </p>
            <p><input type = "text" name="nm"/></p>
            <p><input type = "submit" value="submit"/></p>
        </form>    
    </body>    
</html>

这是 app.py 文件:

from flask import Flask, redirect, url_for, request  
app = Flask(__name__)  
     
@app.route('/success/<name>')  
def success(name):  
    return "Welcome %s" % name

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

    else :
        user = request.args.get('nm')
        return redirect(url_for('success', name = user))    
      
if __name__ == "__main__":  
    app.run(debug = True)

当我在 HTML 登录表单中输入文本并单击 submit 时,它应该已重定向到所需的 URL 但什么也没有发生。

编辑

尝试 Rogan Josh 建议的更改后,出现此错误:

File not found

Firefox can’t find the file at /home/hp/flask_practice/{{ url_for('login') }}.

    Check the file name for capitalization or other typing errors.
    Check to see if the file was moved, renamed or deleted.

您的代码无法执行任何操作,因为您实际上并未从烧瓶应用程序中提供 html。您刚刚 double-clicked 它并在浏览器中打开了 HTML。

您的 html 文件需要放在 app.py 中名为“模板”的子目录中。然后将您的代码更改为:

from flask import Flask, redirect, url_for, request, render_template  
app = Flask(__name__)  
     
@app.route('/success/<name>')  
def success(name):  
    return "Welcome %s" % name

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

    else :
        user = request.args.get('nm') # THIS DOES NOTHING
        return render_template('login.html')  # CHANGED HERE  
      
if __name__ == "__main__":  
    app.run(debug = True)

您还应该将 HTML 更新为:

<html>
    <body>
        <form action="{{ url_for('login') }}" method="POST">
            <p>Enter name : </p>
            <p><input type = "text" name="nm"/></p>
            <p><input type = "submit" value="submit"/></p>
        </form>    
    </body>    
</html>

现在打开浏览器并转到127.0.0.1:5000/login