0

I thought I sort of understood GET and POST requests in that:

  • GET request means the user only retrieves data from the server; cannot change anything like the database
  • POST request means the user can send data to the server and change something

As a final touch, I decided to create a route called /account (added to the navbar next to Log Out) where user can input their old pw, new pw, confirm pw. Then if old pw is in database, they update with new pw.

I set it up like this:

@app.route("/account", methods=["GET", "POST"])
@login_required
def account():
    if request.method == "POST":
        # update pw
        return redirect(url_for("index"))

    else:            
        return redirect(url_for("index"))

When I click "Account" on the navigation bar, it just takes me back to index. I can see why this is happening - clicking Account is a GET request. But if I take out methods specification and just do:

@app.route("/account")
@login_required
def account():
    # update pw
    return redirect(url_for("index"))

I get the following error on my browser:

Bad Request

The browser (or proxy) sent a request that this server could not understand.

I read that if you don't specify GET or POST, it's GET by default. So it makes sense that index(), history(), logout() don't specify methods as they only get back results, not send something to be changed.

I think this is happening because I'm trying to change the database (which should be through a POST request) but I'm sending a GET request? I'm lost on how to implement this route.

0

I suspect the problem is in the # update pw code. If you try to access a non-existent key in request.form (for a POST request) or request.args (GET request) that is precisely the message that is returned. So something like request.args["password"] when there is no key = password will give the Bad Request message. It's described in the Flask Quickstart doc:

What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.

Your understanding of GET and POST sound right. Here's a good description of the difference from among the millions of results for a "GET vs POST" search.

  • I ended up getting it to work by making GET return account.html and POST return index.html after changing the pw. # update pw worked as intended. Instead I think the error was because clicking Account in the navbar directs to url_for('account') as specified in layout.html but nowhere in the 2nd code snippet did I render or direct to account.html. I misunderstood and thought the user getting back the account.html form itself had to be through POST. – 5areductase Sep 11 '17 at 1:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .