Different way of handling POST requests on URL


i have seen two different ways of handling post requests on a route:

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        # insert logic on data
    return render_template('register.html', title="Register", form=form)


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        # insert logic

I cannot seem to find a clear answer to the following questions, and i cant seem to find a duplicate in SO:

  1. Do they refer to different use cases?
  2. Should both be used? Are they

Thanks in advance!


Your first method will execute on either situation: "user requests the data [GET]" or "user posts a form [POST]". Use the second method if want to assign both the GET and POST requests to the same route.

See the code below :

if request.method == "POST":
    # HTTP Method POST. That means the form was submitted by a user
    # and we can find her filled out answers using the request.POST QueryDict
    # Normal GET Request (most likely).
    # We should probably display the form, so it can be filled
    # out by the user and submitted. 

Or you will want to create different route function, one that will post your form and another that will redirect you to get function after you post your data if this is what you are looking for.

@app.route('/register', methods=['POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
         # redirect to '/register_success' with user data

def registration_success():
    # render <You are registered 'user'> --etc--

Answered By – Nabin Paudel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published