gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:54:14 25 4
gpt4 key购买 nike

我知道打开一个文件只会创建一个文件处理程序,无论文件大小如何,它都会占用固定的内存。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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com