user11664462
user11664462

Reputation:

Bad request Flask

I'm new to Flask and i'm trying to build my own flask app. I cannot figure out what cause this error.

400 Bad Request

The browser (or proxy) sent a request that this server could not understand. Here is my python code :

@app.route('/upload1', methods=['POST'] )
def upload1():
    mysql.connection.autocommit(on=True)
    cur = mysql.connection.cursor()
    f = request.files['inputFile']
    r = pd.read_csv(f, sep=',')
    for it in r.iterrows():
       cur.execute('INSERT INTO users(user_name, pass, name, role_id) VALUES(%s, %s, %s, %s)', it[1])

    cur.close()
    flash('Import Success', 'success')
    return redirect(url_for('admin'))

admin.html

{% extends 'layout.html' %}

{% block body %}
    <h1>Admin <small>Welcome {{session.username}}</small></h1>
    <form action="/upload1" method="POST">
        <button name="upload1" type="submit">Upload</button>
    </form>


{% endblock %}

Upvotes: 0

Views: 387

Answers (1)

Josh Honig
Josh Honig

Reputation: 187

f = request.files['inputFile']

I'm not sure if this is the cause of the issue, but it looks like you're trying to read a file submitted with an HTTP POST, but your form content type is not correct. Add enctype="multipart/form-data" as an attribute to your HTML form. In addition, it looks like you're missing a place to upload the file inside of the form.

<form action="/upload1" method="POST">
<!-- Should become -->
<form action="/upload1" method="POST" enctype="multipart/form-data">
<!-- ...and add a file input... -->
<input type="file" name="inputFile"> <!-- note that the name attribute matches the existing python code -->

If this attribute isn't included, the web browser will default to a Content-Type of application/x-www-form-urlencoded, which does not allow for file uploads.

Enabling Flask's debug mode is a good way to get more detailed information on errors. You can do that by modifying your app.run() statement to include the debug parameter, for example:

app.run(debug=True)

Providing the specific exception thrown by Flask with the debug mode enabled will better help us understand the underlying cause of the issue. Hope this helps.

Upvotes: 1

Related Questions