bottlepy / bottle

bottle.py is a fast and simple micro-framework for python web-applications.
http://bottlepy.org/
MIT License
8.33k stars 1.46k forks source link

cannot close body fd auto while upload file #1383

Closed chenming219 closed 2 years ago

chenming219 commented 2 years ago

The example below, have a bug that cannot close body fd and also cannot close upload.file

@route('/upload', method='POST')
def do_upload():
    category   = request.forms.get('category')
    upload     = request.files.get('upload')
    name, ext = os.path.splitext(upload.filename)
    if ext not in ('.png','.jpg','.jpeg'):
        return 'File extension not allowed.'

    save_path = get_save_path_for_category(category)
    upload.save(save_path) # appends upload.filename automatically
    return 'OK'

suggest to change to the following code, or add self.body.close() in POST function and add self.file.close() in save function

@route('/upload', method='POST')
def do_upload():
    category   = request.forms.get('category')
    upload     = request.files.get('upload')
    request.body.close()
    name, ext = os.path.splitext(upload.filename)
    if ext not in ('.png','.jpg','.jpeg'):
        return 'File extension not allowed.'

    save_path = get_save_path_for_category(category)
    upload.save(save_path) # appends upload.filename automatically
    upload.file.close()
    return 'OK'
defnull commented 2 years ago

You can use a with bottle.request.body: block to prevent the resource warning and properly close the request body.

Automatically closing the body after each request would break backwards compatibility because it is currently allowed to move body processing to a separate thread or access the body after the request was already closed.

chenming219 commented 2 years ago

so,follow your suggestion, I suggest to edit the example code for File Uploads in https://bottlepy.org/docs/dev/tutorial.html, This sample code does not close the file handle properly

defnull commented 2 years ago

We have a fix now in master branch that avoids the ResourceWarning. Still not perfect, but It'll do for now.