Home > other >  Which scenarios need the usage of GET and POST methods in the same form?
Which scenarios need the usage of GET and POST methods in the same form?

Time:11-10

I am new to Flask and need some guidance on the usage of GET and POST methods in HTML forms. I understand that POST method offers more security when sending data to the server whereas in GET method, the form inputs are passed in the URL and are visible. However, I have recently come across an example where both methods are being used in the same form and I am trying to understand the utility of defining both methods in the same form.

from flask import Flask, redirect, url_for, render_template, request, abort
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('log_in.html')

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      if request.form['username'] == 'admin' :
         return redirect(url_for('success'))
      else:
         abort(401)
   else:
      return redirect(url_for('index'))

@app.route('/success')
def success():
   return 'logged in successfully'

if __name__ == '__main__':
   app.run(debug = True)

In the statement if request.method == 'POST':, why do we need a conditional check? Is there a possibility that the user filling the form can choose to use GET instead of POST method?

CodePudding user response:

The same route is being used for when the form is loaded and when user enters login data and submits the form.

For example, on the website home page, user clicks on login button and the url behind is /login. This is a GET request and loads the login page with the login form.

User then enters their username and password and clicks on login or submit. This submits the form to the same url i.e. /login but this time, the request is a POST. When Flask sees this is a POST request, it then looks for the user name and password

CodePudding user response:

This is something commonly used in flask / web development in general. Checking the request method offers you the ability to use the route for both

  • showing a page
  • submitting a form

which makes routing a lot cleaner because you don‘t always need both a route for rendering a form and submitting a form and your code doesn‘t get too messy.

  • Related