Python3 Flask将文件上载到服务器内存中 [英] Python3 Flask upload file in server memory

查看:482
本文介绍了Python3 Flask将文件上载到服务器内存中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python3中使用Flask作为Web服务器,并使用Flask的上传功能。将文件上传到服务器会产生 werkzeug.datastructures.FileStorage 对象。



我需要的一个功能这个文件还需要能够从路径对象中打开文件,所以目前我正在使用 open(file_to_open)。如果可能,我想避免将上传的文件写入临时文件,只是再次读取它。所以我的问题由两部分组成:

1:将这个FileStorage对象翻译到一个文件对象是否可能?



2:如果是这样,这是否也适用于当前的代码( open(file_to_open))?

FileStorage 对象的形式呈现的。然而,这并不意味着涉及实际的物理文件。

解析文件对象时,Werkzeug使用 stream_factory()可调用来产生一个文件对象。默认实现只会创建一个实际的文件大小为500kb或以上的物理文件,以避免占用内存。



对于较小的文件,一个in使用内存文件对象。



我不会篡改这个安排。因为它的工作现在的问题是透明地处理,你的硬盘只有当文件上传否则会加重你的记忆。



相反,我会改变函数不需要一个文件名和/或接受一个文件对象。

如果你的函数只能将路径包含的数据作为字符串,你可以通过反省底层的 .stream 属性来看看是否需要读取文件:

  from werkzeug._compat import BytesIO 

filename = data = None
如果file_upload.filename是None:
data = file_upload.read()#in - 内存流,所以读出来。
else:
filename = file_upload.filename


I'm using Flask in Python3 as a webserver, and am using the upload function of Flask. Uploading a file to the server results in a werkzeug.datastructures.FileStorage object.

One of the functions I need this file in, also needs to be able to open files from path objects, so at the moment, I'm using open(file_to_open). If possible, I would like to avoid writing the uploaded file to a temporary file, just to read it in again. So my question consists of two parts:

1: Would it be possible to "translate" this FileStorage object to a file object?

2: If so, would this also work on the current code (open(file_to_open))?

解决方案

Incoming file uploads are indeed presented as FileStorage objects. However, this does not necessarily mean that an actual physical file is involved.

When parsing file objects, Werkzeug uses the stream_factory() callable to produce a file object. The default implementation only creates an actual physical file for file sizes of 500kb and over, to avoid eating up memory.

For smaller files an in-memory file object is used instead.

I'd not tamper with this arrangement; as it works right now the issue is handled transparently and your harddisk is only involved when the file uploads would otherwise tax your memory too much.

Rather, I'd alter that function to not require a filename and / or accept a file object.

If your function can only take a path or the contained data as a string, you can see if you need to read the file by introspecting the underlying .stream attribute:

from werkzeug._compat import BytesIO

filename = data = None
if file_upload.filename is None:
    data = file_upload.read()  # in-memory stream, so read it out.
else:
    filename = file_upload.filename

这篇关于Python3 Flask将文件上载到服务器内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆