Python Bottle - 如何在不关闭服务器的情况下上传媒体文件

2024-01-31

我正在使用来自的答案这个问题 https://stackoverflow.com/questions/14296438/bottle-file-upload-and-process并看到评论:

   raw = data.file.read() # This is dangerous for big files

如果不这样做,如何上传文件?到目前为止我的代码是:

@bottle.route('/uploadLO', method='POST')
def upload_lo():
    upload_dir = get_upload_dir_path()
    files = bottle.request.files
    print files, type(files)
    if(files is not None):
        file = files.file
        print file.filename, type(file)
        target_path = get_next_file_name(os.path.join(upload_dir, file.filename))
        print target_path
        shutil.copy2(file.read(), target_path)  #does not work. Tried it as a replacement for php's move_uploaded_file
    return None

这给出了这个输出:

127.0.0.1 - - [03/Apr/2014 09:29:37] "POST /uploadLO HTTP/1.1" 500 1418
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\bottle.py", line 862, in _handle
    return route.call(**args)
  File "C:\Python27\lib\site-packages\bottle.py", line 1727, in wrapper
    rv = callback(*a, **ka)
  File "C:\dev\project\src\mappings.py", line 83, in upload_lo
    shutil.copy2(file.read(), target_path)
AttributeError: 'FileUpload' object has no attribute 'read'

我正在使用 python Bottle v.12、dropzone.min.js 和 mongodb。我也在使用这个教程:

http://www.startutorial.com/articles/view/how-to-build-a-file-upload-form-using-dropzonejs-and-php http://www.startutorial.com/articles/view/how-to-build-a-file-upload-form-using-dropzonejs-and-php


这称为“文件吞吐”:

raw = data.file.read() 

and 你不想这样做 http://axialcorps.com/2013/09/27/dont-slurp-how-to-read-files-in-python/(至少在这种情况下)。

这是读取未知(可能很大)大小的二进制文件的更好方法:

data_blocks = []

buf = data.file.read(8192)
while buf:
    data_blocks.append(buf)
    buf = data.file.read(8192)

data = ''.join(data_blocks)

如果累积大小超过某个阈值,您可能还想停止迭代。

希望有帮助!


PART 2

您询问有关限制文件大小的问题,因此这里有一个修改版本:

MAX_SIZE = 10 * 1024 * 1024 # 10MB
BUF_SIZE = 8192

# code assumes that MAX_SIZE >= BUF_SIZE

data_blocks = []
byte_count = 0

buf = f.read(BUF_SIZE)
while buf:
    byte_count += len(buf)

    if byte_count > MAX_SIZE:
        # if you want to just truncate at (approximately) MAX_SIZE bytes:
        break
        # or, if you want to abort the call
        raise bottle.HTTPError(413, 'Request entity too large (max: {} bytes)'.format(MAX_SIZE))

    data_blocks.append(buf)
    buf = f.read(BUF_SIZE)

data = ''.join(data_blocks)

它并不完美,但它很简单,而且在我看来已经足够好了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python Bottle - 如何在不关闭服务器的情况下上传媒体文件 的相关文章

随机推荐