How to safely check the size of the downloaded file in the bottle?

I am really afraid of this operation read()because it uses memory. For example, can someone DDoS my server by downloading a 1gb file, fix it?

name = request.forms.get('name')
data = request.files.get('data')
if name and data.file:
    raw = data.file.read() # This is dangerous for big files
    filename = data.filename
    return "Hello %s! You uploaded %s (%d bytes)." % (name, filename, len(raw))

Is there any safe solution to get the size of the downloaded file? It was assumed that the file size would be equal to the file system; request.files.get('data')probably stored somewhere in the temp file right?

+5
source share
2 answers

You can check if you can read pieces of data one at a time.

If possible, then:

name = request.forms.get('name')
data = request.files.get('data')
raw = ""
if name and data.file:
    while True:
        datachunk = data.file.read(1024)
        if not datachunk:
            break
        raw = raw + datachunk

    filename = data.filename
    return "Hello %s! You uploaded %s (%d bytes)." % (name, filename, len(raw))

If possible, you can also add a tracking mechanism for how large the file you want to read and if exceeded abort this operation.

, DDOS.

+2

. os.path . .

, , . , - JavaScript. , JavaScript BottlePy.

JavaScript , , . , BottlePy BaseRequest.files.

-3

All Articles