首页 > 解决方案 > 为什么我的 HTTP Post 在烧瓶中不起作用?

问题描述

我有我的 Flask 应用程序,其profile功能如下:

@app.route('/profile/')
def profile(username, password):
    return f"<h1>username entered: {username} password entered: {password}</h1>"

我也有我的login函数,它login.html用作模板,并使用 andprofile重定向usernamepassword

这是我的登录功能:

@app.route('/login/', methods=['POST', 'GET'])
def login():
    if request.method == "GET":
        return render_template('login.html')
    elif request.method == "POST":
        username = request.form['username']
        password = request.form['password']
        print(f'Username: {username}, Password: {password}')
        return redirect(url_for('profile', username=username, password=password))

这是我的index.html文件(只有正文部分)

<h1>Login</h1>
<form action="#" method="POST">
    <label>Username</label>
    <input type="text" name="username">
    <label>Password</label>
    <input type="password" name="password">
    <button>Submit</button>
</form>

但是,当我尝试登录然后提交时,我得到一个 TypeError,说我的profile函数缺少两个参数。我得到了要在终端上打印的用户名和密码,所以我知道我的登录功能运行良好。为什么会出现此错误,我该如何解决?

标签: pythonpython-3.xhttpflaskpost

解决方案


profile 函数中的参数应与 url 参数相对应。您需要像这样更新 URL:

@app.route('/profile/<string:username>/<string:password>')
def profile(username, password):
    return f"<h1>username: {username} password entered: {password}</h1>

一个更实际的 url 参数使用例如:在给定用户 id 的情况下获取用户的个人资料

@app.route('/profile/<int:userId>', methods=["GET"])
def profile(userId):
    user = getUserById(userId) 
    return f"<h1>username: {user["username"]}. userId: {user["id"]}</h1>

理论上,请求如下所示:GET /profile/20 响应:<h1>username: foo. userId: 20</h1>


推荐阅读