I am building a simple website with Flask, where the user login form is available in the upper right corner, no matter on which url the user currently is (html form is defined in my base.html template, which is extended by all other templates). So one of the choices to make it work, is to handle the login form in each @app.route() method, but it adds a lot of redundant code, it looks ugly, and I'm looking for a way to simplify it.
So my question is: Is it possible to create one method that will handle the login form for each endpoint in my application?
Here is some code of my login form:
@app.route('/', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user, remember=True)
return redirect(url_for('home'))
return render_template('index.html', form=form)
And here is the screenshot of the rendered form itself:
https://i.stack.imgur.com/PXNSB.png
Aucun commentaire:
Enregistrer un commentaire