werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: I am not able to figure why I am getting this error

Question:

I am requesting a file to be uploaded but I get a keyerror even though I have name="imagefile" in my form.

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/',methods=['GET'])


@app.route('/', methods=["POST"])
def predict():
    imagefile = request.files['imagefile']
    image_path = "./images/"+imagefile.filename
    imagefile.save(image_path)

    return render_template('index.html')

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


<!DOCTYPE html>
<html>
    <head>
        <title>Tutorial</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    </head>

    <body>
        <h1>Image Classifer</h1>

        <form class="p-3 text-center" action='/', method=""post enctype="multipart/form-data"> 
            <input class="form-control" type="file" name='imagefile' >
            <input class="btn btn-primary mt-3" type="submit" value="Predict Image" >
        </form>
    </body>
</html>

I am not sure why it is not detecting imagefile… Does anyone know how to fix this?

Asked By: NavoNator3000

||

Answers:

You aren’t correctly setting your GET and POST methods for your single route. In addition to this, you also need some logic on your route to handle the POST request from your form.

from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/', methods=["GET", "POST"])
def predict():
    if request.method == "POST":
        imagefile = request.files['imagefile']
        image_path = "./images/" + imagefile.filename
        imagefile.save(image_path)

    return render_template('index.html')


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

I also noticed that you have a typo in your form method attribute.

<form class="p-3 text-center" action='/' method="POST" enctype="multipart/form-data">
Answered By: Undesirable
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.