python - 为什么我的 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
重定向username
到password
。
这是我的登录功能:
@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
函数缺少两个参数。我得到了要在终端上打印的用户名和密码,所以我知道我的登录功能运行良好。为什么会出现此错误,我该如何解决?
解决方案
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>
推荐阅读
- c - 并行计时器创建使内核崩溃
- c# - LINQ group by 加入并计算同一项目的出现次数
- excel - 筛选包含各种字符组合的单元格的 Excel 列
- java - @NotNull 什么时候会抛出异常?
- python - 检查页面上是否存在 h1 或 h2
- windows - 如果之前返回错误,再次调用 Win32 FlushFileBuffers() 函数是否安全?
- elasticsearch - Elasticsearch 不会更新结果
- c# - 如何使用单个文本框将多个不同的数字(整数)传递到数组中?C#
- python - 为什么外部进口对烧瓶不起作用?
- python - Scipy.minimize 中不支持约束