0

Here is a way to accept upload with Bottle:

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
</form>

and

from bottle import route, request

@route('/upload', method='POST')
def do_upload():
    myfile = request.files.get('file')
    size = len(myfile.read())  # oops the file is already read anyway!
    if size > 1024*1024:  # 1 MB
        return "File too big"

However, with this technique a 500 MB file would be read anyway, before noticing it's a "too big file".

Question: how to prevent a Bottle server to even accept a too big uploaded file, without having to read it first (and waste bandwidth/memory!)?

If not possible with Bottle only, how to do it with Apache + mod_wsgi (I currently use this)?

Basj
  • 41,386
  • 99
  • 383
  • 673
  • You can first read header "Content-Length" to determine drop it or not. But you cannot avoid wasting bandwidth. – Sraw Jun 20 '18 at 09:25
  • @Sraw when reading "Content-Length", the 500 MB would already be uploaded to server, so that's too late, the file is already on server, isn't there a way to know this earlier and refuse it? – Basj Jun 20 '18 at 09:31
  • It doesn't seem to be possible in pure bottle. Maybe you should consider to use nginx as a frontend server which is usually used in production. – Sraw Jun 20 '18 at 09:39
  • @Sraw I'm using Apache with mod_wsgi, would you know how to do it? – Basj Jun 20 '18 at 09:46

1 Answers1

0

Because you are using Apache, you can add to the Apache configuration the LimitRequestBody directive and specify the limit. The request will be rejected before it even gets to your Python code.

Graham Dumpleton
  • 57,726
  • 6
  • 119
  • 134