I'm trying to learn more about Flask for a project, and I'm wondering if someone can explain to me why the sample code lists the methods 'GET' and 'POST', when it only ever tries to process a login if the request was 'POST'?
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
# Note that nowhere do we seem to care about 'GET'...
return render_template('login.html', error=error)
GET and POST methods are both handled by your function.
When GET is used, the login form (login.html
) is returned for the user to log in. This is the last line of the function.
When POST is used, the form is validated using provided login/password. After that the user is either redirected to an other page (url for show_entries
) or the login form is sent another time with the related error.
You should read 'When do you use POST and when do you use GET?' for more details on why POST is used to process the login form and why GET is used to send it.
return render_template('login.html', error=error)
is the handler for GET
.
Think about the logic:
render_template
gets those errors, otherwise it gets the None
from the beginning of the method. I assume that if error is None
in render_template
it probably just renders a plain ol' login form.Note: I've never used flask, but I understand python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With