7

I have a file upload handler for multiple file uploads, and have set the MAX_CONTENT_SIZE. The docs mention that Flask throws a 413 exception when the total file size exceeds the limit, so I've also written a 413 error handler with a custom 413 page. However, when testing the file upload, I can see that the 413 error is definitely thrown, but the connection seems to break everytime instead of rendering my error page. FYI, I'm using the Flask dev server currently.

Code:

app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024    # 50 Mb limit

@app.route('/upload', methods=['POST'])
def upload_files():
    if request.method == 'POST':
       uploaded_files = request.files.getlist('uploaded_files[]')

       # do some stuff with these files



@app.errorhandler(413)
def error413(e):
    return render_template('413.html'), 413

UPDATE:

Ok strange, this problem seems to only occur when using the Flask dev server. I'm testing it on Apache, and my 413 error page renders fine.

rottentomato56
  • 951
  • 2
  • 12
  • 18
  • Hey, check the comments in the answer in this question: http://stackoverflow.com/questions/14000569/can-we-count-the-upload-filesize-before-uploading-in-python-flask, there are some good pointers – jbub Nov 11 '13 at 19:33
  • Did you check your apache configuration? May be maximum upload limit of apache is breaking connection. – Prakash Pandey Jun 11 '15 at 20:53
  • 1
    Large file uploads are wonky when using the Flask dev server. Just ran into a similar issue, which was fixed by running the app with Gunicorn. – nathancahill Jul 15 '15 at 23:18
  • Please check my answer [here](https://stackoverflow.com/a/49332379/5511849). – Grey Li Mar 17 '18 at 04:19
  • Check Connection Reset Issue here in documentation: http://flask.pocoo.org/docs/1.0/patterns/fileuploads/#improving-uploads – Shubham Oct 01 '18 at 06:28

1 Answers1

0

Use a production WSGI server will solve this problem (e.g. Gunicorn, Waitress). Below is a simple timeline of this issue.

2015

In this snippet (gone) that posted by Armin Ronacher, he said:

You might notice that if you start not accessing .form or .files on incoming POST requests, some browsers will honor this with a connection reset message. This can happen if you start rejecting uploads that are larger than a given size.

Some WSGI servers solve that problem for you, others do not. For instance the builtin Flask webserver is pretty dumb and will not attempt to fix this problem.

2018

I added a tip in the Flask's file uploading docs (flask #2662):

Connection Reset Issue

When using the local development server, you may get a connection reset error instead of a 413 response. You will get the correct status response when running the app with a production WSGI server.

2021

I think/hope it will be fixed in Werkzeug in the near future (werkzeug #1513).

Grey Li
  • 7,945
  • 1
  • 38
  • 53