Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open and read file from request.FILES without saving it to disk

Tags:

Is there a way to treat a file in request.FILES same as a disk file? I want to do something like this:

with open(file_in_request, 'rb') as file:
        #read data from that file

Only, I don't want to have to save it to disk first. I will be encrypting that file and save the encrypted file to disk instead.

like image 625
Tahreem Iqbal Avatar asked Nov 30 '17 06:11

Tahreem Iqbal


1 Answers

TLDR: by modifying FILE_UPLOAD_MAX_MEMORY_SIZE Django variable to a large enough value to keep files in memory.


By default, Django stores file with a size of 2.5 MB in memory and file larger than that size are stored in a temporary disk location.

The reason for this behavior is that keeping large files in memory can overwhelm your system. Read it here in docs.

In your case, if you know the max file size and are sure that it won't be large enough to fill up your computer memory you can modify the threshold value FILE_UPLOAD_MAX_MEMORY_SIZE variable to a large enough value to make sure all the files are in memory.

From the docs:

The maximum size (in bytes) that an upload will be before it gets streamed to the file system. See Managing files for details

like image 53
Amit Tripathi Avatar answered Sep 21 '22 12:09

Amit Tripathi