python - InMemoryUploadedFile 真的是 "in memory"吗?

标签 python django memory-management

我知道打开一个文件只会创建一个文件处理程序,无论文件大小如何,它都会占用固定的内存。 Django 有一个名为 InMemoryUploadedFile 的类型,它表示通过表单上传的文件。

我像这样在 Django View 中获取我的文件对象的句柄:

file_object = request.FILES["uploadedfile"]

此 file_object 的类型为 InMemoryUploadedFile

现在我们可以自己看到,file_object 有方法.read() 用于将文件读入内存。

bytes = file_object.read()

类型InMemoryUploadedFilefile_object 不是已经“在内存中”了吗?

最佳答案

文件对象的 read() 方法是一种从文件对象中访问内容的方法,无论该文件是在内存中还是存储在磁盘上。它类似于其他实用程序文件访问方法,如 readlinesseek

行为类似于 built into Python 又是基于操作系统的 fread() 方法构建的。

Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.

关于InMemoryUploadedFile 究竟存储在哪里的问题,它是一个bit more complicated。 .

Before you save uploaded files, the data needs to be stored somewhere.

By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold the entire contents of the upload in memory. This means that saving the file involves only a read from memory and a write to disk and thus is very fast.

However, if an uploaded file is too large, Django will write the uploaded file to a temporary file stored in your system’s temporary directory. On a Unix-like platform this means you can expect Django to generate a file called something like /tmp/tmpzfp6I6.upload. If an upload is large enough, you can watch this file grow in size as Django streams the data onto disk.

These specifics – 2.5 megabytes; /tmp; etc. – are simply “reasonable defaults”. Read on for details on how you can customize or completely replace upload behavior.

关于python - InMemoryUploadedFile 真的是 "in memory"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20827939/

相关文章:

python - 从一维循环创建 n 维网格的公式是什么?

python - Django 在使用 matplotlib 示例时出错

android - 布局内存泄漏?

python - 无法使用 boto3 更新 Route 53 上的 DNS 记录

python - 在 Python 中,如何从 argparse 深度复制 Namespace obj "args"

python - Selenium +python : Waiting on changes in style

python - Django 模型字段默认基于同一模型中的另一个字段

python - 评级模型 Django

iPhone 内存泄漏

java - Android应用程序上的DeadObjectException