Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the login method of Flask use 'GET'?

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)
like image 835
Eric Hydrick Avatar asked May 21 '12 13:05

Eric Hydrick


2 Answers

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.

like image 98
math Avatar answered Sep 27 '22 23:09

math


return render_template('login.html', error=error) is the handler for GET.

Think about the logic:

  1. if request.method == 'POST':
    1. Check Credentials, Set error method
    2. If no credential errors return the correct redirect
  2. if there were errors in the POST section of code 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

like image 27
Chris Pfohl Avatar answered Sep 27 '22 23:09

Chris Pfohl