[英]How to make a route function in Flask run every time a form is loaded
我有一個簡單的表單,在 Flask 中有一個密碼字段,應該有有限的機會(10)正確提交。 問題是,即使每次提交的值不正確時我都會將chances
變量減去 1,但chances
只會減去一次(它在 9 處停止),無論我提交多少次表單並刷新頁面。
這是我的路線:
@app.route('/administrator-login', methods=['GET','POST'])
def admin_login():
if current_user.is_authenticated:
return redirect('/administrator-logout')
form = AdminLogin()
user = User.query.first()
if form.validate_on_submit():
if user.chances <= 0:
return render_template(url_for('home'))
if user and form.password.data == 'password': # I will hash the actual password later
user.chances = 10
login_user(user)
return redirect('/hack-the-site-here')
elif form.password.data != 'password':
user.chances -= 1
return render_template('admin_login.html', form=form, chances=user.chances)
這是我的表格:
class AdminLogin(FlaskForm):
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
'admin_login.html'
文件
<h3>Chances left: {{ chances }}</h3>
<div class="mt-3">
<form method="POST" action="">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Admin Login</legend>
<div class="form-group">
{{ form.password.label(class="form-control-label") }}
{% if form.password.errors %}
{{ form.password(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.password.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.password(class="form-control form-control-lg") }}
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info btn-lg") }}
</div>
</form>
</div>
</div>
這是User
class:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
chances = db.Column(db.Integer)
數據庫中只有一個User
object 並且不應更改。 接受批評和建議。 我懷疑這與user.chances
存儲在用戶 object 中的方式有關。 您還需要其他信息嗎? 提前致謝。
您還需要在更改chances
屬性后更新 DB 中的機會值。
@app.route('/administrator-login', methods=['GET','POST'])
def admin_login():
if current_user.is_authenticated:
return redirect('/administrator-logout')
form = AdminLogin()
user = User.query.first()
if form.validate_on_submit():
if user.chances <= 0:
return render_template(url_for('home'))
if user and form.password.data == 'password': # I will hash the actual password later
user.chances = 10
db.session.commit()
login_user(user)
return redirect('/hack-the-site-here')
elif form.password.data != 'password':
user.chances -= 1
db.session.commit()
return render_template('admin_login.html', form=form, chances=user.chances)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.