[英]How to change to message when page is refreshed in flask?
app.py 是:在此我使用 yash 和 yash 作为默认用户名和密码,当我输入错误密码并输入密码时,html 页面打印“无效凭据”。 但是,当我在获得无效凭据后刷新时,它也显示相同的 index.html 页面,其中显示“无效凭据”消息。 当我从浏览器刷新页面时,我该怎么做才能显示空的登录页面。
import flask
app = flask.Flask(name)
u_p={'yash':'yash'}
@app.route('/user/<name>')
def hello_user(name):
return flask.render_template('hello.html',uname=name)
@app.route('/', methods=['GET', 'POST'])
def index():
message = ''
if flask.request.method == 'POST':
username=flask.request.form['name-input']
passowrd=flask.request.form['name-password']
if u_p.get(username,'')==passowrd:
return flask.redirect(flask.url_for('hello_user',name=username))
else:
message='Invalid Credentials'
return flask.render_template('index.html', message=message)
if name == 'main':
app.run()
我的 index.html 是:
<!DOCTYPE html>
<html>
<head>
<title>Simple Flask App</title>
<link rel="shortcut icon" href="{{url_for('static', filename='favicon.png')}}" type="image/x-icon">
</head>
<body>
<h1>Login</h1>
<form method="POST">
username <input type="text" name="name-input"><br>
password <input type="password" name="name-password"><br>
<button type="submit">Submit</button>
</form>
<h2>New User : </h2>
<button type="submit">Register</button>
<p>{{message}}</p>
</body>
</html>
问题是,如果您刷新页面,浏览器会再次发送相同的 POST 请求,因此就像您再次尝试使用相同的错误凭据登录一样。
如果凭据错误,您可以通过重定向到索引来解决此问题 - 但是您不能将消息作为模板参数传递。
幸运的是,flask 正好为此目的提供消息闪烁: https://flask.palletsprojects.com/en/2.0.x/patterns/flashing/
所以你的代码可能看起来像这样:
import flask
name = "main"
app = flask.Flask(name)
app.secret_key = "SECRET!"
u_p={'yash':'yash'}
@app.route('/user/<name>')
def hello_user(name):
return flask.render_template('hello.html',uname=name)
@app.route('/', methods=['GET', 'POST'])
def index():
if flask.request.method == 'POST':
username=flask.request.form['name-input']
passowrd=flask.request.form['name-password']
if u_p.get(username,'')==passowrd:
return flask.redirect(flask.url_for('hello_user',name=username))
else:
flask.flash("Invalid Credentials")
return flask.redirect(flask.url_for("index"))
return flask.render_template('index.html')
if name == 'main':
app.run()
索引.html
<!DOCTYPE html>
<html>
<head>
<title>Simple Flask App</title>
<link rel="shortcut icon" href="{{url_for('static', filename='favicon.png')}}" type="image/x-icon">
</head>
<body>
<h1>Login</h1>
<form method="POST">
username <input type="text" name="name-input"><br>
password <input type="password" name="name-password"><br>
<button type="submit">Submit</button>
</form>
<h2>New User : </h2>
<button type="submit">Register</button>
{% with messages = get_flashed_messages() %}
{% for message in messages %}
<p>{{message}}</p>
{% endfor %}
{% endwith %}
</body>
</html>
附带说明:检查用户名和密码的方式是,有人可以使用随机用户名和空密码登录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.