django.core.files.uploadedfile - InMemoryUploadedFile

Dongwoo Kim·2024년 10월 31일
0

TIL / WIL

목록 보기
122/126

개요

django에서 form_data 형식으로 이미지를 입력받는 api를 구현하게되었는데 이때 해당 데이터가 InMemoryUploadedFile 클래스 인스턴스로 할당되는걸 발견했다.

InMemoryUploadedFile

A file uploaded into memory (i.e. stream-to-memory). This class is used by the MemoryFileUploadHandler.

쉽게말해 메모리에 저장된 파일 객체다. 코드를 보면

[docs]class InMemoryUploadedFile(UploadedFile):
    """
    A file uploaded into memory (i.e. stream-to-memory).
    """

    def __init__(
        self,
        file,
        field_name,
        name,
        content_type,
        size,
        charset,
        content_type_extra=None,
    ):
        super().__init__(file, name, content_type, size, charset, content_type_extra)
        self.field_name = field_name

    def open(self, mode=None):
        self.file.seek(0)
        return self

    def chunks(self, chunk_size=None):
        self.file.seek(0)
        yield self.read()

    def multiple_chunks(self, chunk_size=None):
        # Since it's in memory, we'll never have multiple chunks.
        return False

와 같이 UploadedFile 클래스를 상속받고 있다. 따라서 UploadedFile 클래스에 대해 알아볼 필요가 있다.

UploadedFile

class UploadedFile[source]

During file uploads, the actual file data is stored in request.FILES. Each entry in this dictionary is an UploadedFile object (or a subclass) – a wrapper around an uploaded file. You’ll usually use one of these methods to access the uploaded content:

UploadedFile.read()Read the entire uploaded data from the file. Be careful with this method: if the uploaded file is huge it can overwhelm your system if you try to read it into memory. You’ll probably want to use chunks() instead; see below.

UploadedFile.multiple_chunks(chunk_size=None)Returns True if the uploaded file is big enough to require reading in multiple chunks. By default this will be any file larger than 2.5 megabytes, but that’s configurable; see below.

UploadedFile.chunks(chunk_size=None)A generator returning chunks of the file. If multiple_chunks() is True, you should use this method in a loop instead of read().
In practice, it’s often easiest to use chunks() all the time. Looping over chunks() instead of using read() ensures that large files don’t overwhelm your system’s memory.

Here are some useful attributes of UploadedFile:

UploadedFile.nameThe name of the uploaded file (e.g. my_file.txt).

UploadedFile.sizeThe size, in bytes, of the uploaded file.

UploadedFile.content_typeThe content-type header uploaded with the file (e.g. text/plain or application/pdf). Like any data supplied by the user, you shouldn’t trust that the uploaded file is actually this type. You’ll still need to validate that the file contains the content that the content-type header claims – “trust but verify.”

UploadedFile.content_type_extraA dictionary containing extra parameters passed to the content-type header. This is typically provided by services, such as Google App Engine, that intercept and handle file uploads on your behalf. As a result your handler may not receive the uploaded file content, but instead a URL or other pointer to the file (see RFC 2388).

UploadedFile.charsetFor *text/ content-types, the character set (i.e. utf8**) supplied by the browser. Again, “trust but verify” is the best policy here.

[docs]class UploadedFile(File):
    """
    An abstract uploaded file (``TemporaryUploadedFile`` and
    ``InMemoryUploadedFile`` are the built-in concrete subclasses).

    An ``UploadedFile`` object behaves somewhat like a file object and
    represents some file data that the user submitted with a form.
    """

    def __init__(
        self,
        file=None,
        name=None,
        content_type=None,
        size=None,
        charset=None,
        content_type_extra=None,
    ):
        super().__init__(file, name)
        self.size = size
        self.content_type = content_type
        self.charset = charset
        self.content_type_extra = content_type_extra

    def __repr__(self):
        return "<%s: %s (%s)>" % (self.__class__.__name__, self.name, self.content_type)

    def _get_name(self):
        return self._name

    def _set_name(self, name):
        # Sanitize the file name so that it can't be dangerous.
        if name is not None:
            # Just use the basename of the file -- anything else is dangerous.
            name = os.path.basename(name)

            # File names longer than 255 characters can cause problems on older OSes.
            if len(name) > 255:
                name, ext = os.path.splitext(name)
                ext = ext[:255]
                name = name[: 255 - len(ext)] + ext

            name = validate_file_name(name)

        self._name = name

    name = property(_get_name, _set_name)

Example

  • request
  • api view
    // views.py
    from django.core.files.uploadedfile import InMemoryUploadedFile
    
    class ExampleView(APIView):
        def post(self, request):
    			  data = request.data
    			  image_file: InMemoryUploadedFile = data.get("image_file")
    			  
    			  print(f"file name: {image_file.name}")
    				...
    
  • terminal
    file name: psbg.png

Reference.

https://docs.djangoproject.com/en/5.0/ref/files/uploads/#django.core.files.uploadedfile.InMemoryUploadedFile

https://docs.djangoproject.com/en/5.0/_modules/django/core/files/uploadedfile/

profile
kimphysicsman

0개의 댓글