I am setting a file limit in Flask. When files are uploaded it correctly blocks files over 4mb and returns a 413 error. However this is closing the connection on the server which means that the redirect doesn't work. What I want to do is keep the connection open on this error so I can then redirect the user.
My file size limit is set as:
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024
The code which captures the exception is:
try:
form = FileUploadForm();
except Exception as e:
print(e)
flash(u"File size too large: please choose a file under 4mb","danger")
return redirect(url_for("home"))
This is the exception returned:
413 Request Entity Too Large: The data value transmitted exceeds the capacity limit.
The code "return redirect(url_for("home"))" doesn't work, I believe because the connection is closed on error 413. This is Flask running in development mode.
I have tried the code in the suggested answer, but that doesn't seem to work. My code now looks like:
@app.errorhandler(413)
def largefile_error(e):
print("Large file")
return redirect(url_for("addsign")), 413
@app.route('/addsign', methods=['GET', 'POST'])
def addsign():
if not current_user.is_authenticated:
flash(f"Please login to upload a sign","danger")
return redirect(url_for('home'))
form = FileUploadForm()
In the console I can see the following output.
Large file
127.0.0.1 - - [13/Jul/2020 18:02:34] "POST /addsign HTTP/1.1" 413 -