Why does the flash drive login method use "GET"?

I am trying to learn more about Flask for a project, and I wonder if someone can explain to me why the "GET" and "POST" methods are listed in the sample code when it only ever tries to process 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) 
+6
source share
2 answers

The GET and POST methods are handled by your function.

  • When using GET to log in, the login form ( login.html ) is login.html . This is the last line of the function.

  • When POST is used, the form is validated using the provided username / password. After that, the user is either redirected to another page (url for show_entries ), or the login form is sent at another time with an associated error.

You should read ' When do you use POST and when do you use GET? 'for more information on why POST is used to process the login form and why GET is used to submit.

+8
source

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

Think about the logic:

  • if request.method == 'POST':
    • Check credentials, set error method
    • If credential errors do not return the correct redirect
  • if there were errors in the POST section of the render_template code, it gets these errors, otherwise it gets None from the beginning of the method. I guess if the error is None in render_template , it probably just displays a simple login form.

Note: I've never used flask, but I understand python

+5
source

Source: https://habr.com/ru/post/916258/


All Articles