Home > database >  Flask, post method, request.form, development server
Flask, post method, request.form, development server

Time:07-01

My python code


    if request.method == 'POST':
        if request.form['submit_post'] == 'Submit post':
            print('Hello')
        elif request.form['print_posts'] == 'Print posts':
            print('Bye')
        else:
            print("malformed")
            pass 

My HTML code


    <form action='/' method='post'>
        <input placeholder='Name' name='name'>
        <input placeholder='Post Content' name='post'>
        <input type= "submit" name="submit_post" value='Submit post'>
    </form>
    <form action='/' method='post'>
         <input type= "submit" name="print_posts" value="Print posts"> 
         <!-- To make the program print all the posts in the database -->
    </form> 

The issue is that when the "print_posts" button is pressed it activates the elif "print_posts" part of the if request.method == 'POST': then I get Bad request or this picture 400 Bad Request.

The really strange thing is when I move the print_posts if statement to be the 1st line in the if request.method == 'POST': Shown in the code right below.


    if request.method == 'POST':
        if request.form['print_posts'] == 'Print posts':
            print('Bye')
        elif request.form['submit_post'] == 'Submit post':
            print('Hello')
        else:
            print("malformed")
            pass 

now the print_posts if statement works and the submit_posts if the statement doesn't work.

I also researched the issue and found answers saying the indentation was to blame, but it looks correct

CodePudding user response:

Your flask code assumes that both 'print_posts' and 'submit_posts' are in the request. However, your html only sends one of the two. It fails when it's checking for the incorrect key first. So your flask code probably fails with a key error.

You need to check to see if the key is in the request.form array first: the python idiom is to say "if my_key in my_dict:"

if request.method=='POST':
    if 'print_posts' in request.form:
        # do something with request.form['print_posts']
    elif 'submit_posts' in request.form:
        # do something with request.form['submit_posts']
    else:
        # error

If you get a chance, look at the incoming requests is a python debugger. That will give you a better understanding of what your webpage is sending to you.

  • Related