Python 文件描述符打开和关闭操作,用于按块上传文件



我正在研究将http文件上传到服务器。为了处理大文件,我正在使用块上传,其中文件被分成 1MB 的块,并作为 POST 请求同步发送到后端服务器。在后端瓶子服务器上,我接收块并使用file.write将其附加到新文件中。

@route('file_upload', method = 'POST')
def file_upload():
file_content = request.body`enter code here`
with open(dst_path,'ab') as dst_file_obj:
dst_file_obj.write(file_content.read())
dst_file_obj.close()

但是每次我收到块时打开和关闭文件描述符是一项昂贵的操作。现在,如何在第一个块上打开文件并在接收最后一个字节块时关闭,而无需打开和关闭我收到的特定文件的每个块?

不知道细节,这行不通吗?

@route('file_upload', method = 'POST')
def file_upload():
file_content = request.body`enter code here`
with open(dst_path,'ab') as dst_file_obj:
for chunk in file_content:
dst_file_obj.write(chunk)
# dst_file_obj.close() #< not needed gets closed when with is left

最新更新