v0.166.0
  1"""
  2Base file upload handler classes, and the built-in concrete subclasses
  3"""
  4
  5import os
  6from abc import ABC, abstractmethod
  7from io import BytesIO
  8from typing import TYPE_CHECKING
  9
 10from plain.internal.files.uploadedfile import (
 11    InMemoryUploadedFile,
 12    TemporaryUploadedFile,
 13    UploadedFile,
 14)
 15from plain.runtime import settings
 16
 17if TYPE_CHECKING:
 18    from typing import Any
 19
 20    from plain.http import Request
 21
 22
 23class UploadFileException(Exception):
 24    """
 25    Any error having to do with uploading files.
 26    """
 27
 28
 29class StopUpload(UploadFileException):
 30    """
 31    This exception is raised when an upload must abort.
 32    """
 33
 34    def __init__(self, connection_reset: bool = False) -> None:
 35        """
 36        If ``connection_reset`` is ``True``, Plain knows will halt the upload
 37        without consuming the rest of the upload. This will cause the browser to
 38        show a "connection reset" error.
 39        """
 40        self.connection_reset = connection_reset
 41
 42    def __str__(self) -> str:
 43        if self.connection_reset:
 44            return "StopUpload: Halt current upload."
 45        else:
 46            return "StopUpload: Consume request data, then halt."
 47
 48
 49class SkipFile(UploadFileException):
 50    """
 51    This exception is raised by an upload handler that wants to skip a given file.
 52    """
 53
 54
 55class StopFutureHandlers(UploadFileException):
 56    """
 57    Upload handlers that have handled a file and do not want future handlers to
 58    run should raise this exception instead of returning None.
 59    """
 60
 61
 62class FileUploadHandler(ABC):
 63    """
 64    Base class for streaming upload handlers.
 65    """
 66
 67    chunk_size = 64 * 2**10  # : The default chunk size is 64 KB.
 68
 69    def __init__(self, request: Request) -> None:
 70        self.file_name = None
 71        self.content_type = None
 72        self.content_length = None
 73        self.charset = None
 74        self.content_type_extra = None
 75        self.request = request
 76
 77    def handle_raw_input(
 78        self,
 79        input_data: Any,
 80        boundary: bytes,
 81        encoding: str | None = None,
 82    ) -> None:
 83        """
 84        Handle the raw input from the client.
 85
 86        Parameters:
 87
 88            :input_data:
 89                An object that supports reading via .read().
 90            :boundary:
 91                The boundary from the Content-Type header. Be sure to
 92                prepend two '--'.
 93            :encoding:
 94                The encoding of the request data.
 95
 96        Note: Access self.request for content_length, environ, or other request data.
 97        """
 98
 99    def new_file(
100        self,
101        field_name: str,
102        file_name: str,
103        content_type: str,
104        content_length: int | None,
105        charset: str | None = None,
106        content_type_extra: dict[str, str] | None = None,
107    ) -> None:
108        """
109        Signal that a new file has been started.
110
111        Warning: As with any data from the client, you should not trust
112        content_length (and sometimes won't even get it).
113        """
114        self.field_name = field_name
115        self.file_name = file_name
116        self.content_type = content_type
117        self.content_length = content_length
118        self.charset = charset
119        self.content_type_extra = content_type_extra
120
121    @abstractmethod
122    def receive_data_chunk(self, raw_data: bytes, start: int) -> bytes | None:
123        """
124        Receive data from the streamed upload parser. ``start`` is the position
125        in the file of the chunk.
126        """
127        ...
128
129    @abstractmethod
130    def file_complete(self, file_size: int) -> UploadedFile | None:
131        """
132        Signal that a file has completed. File size corresponds to the actual
133        size accumulated by all the chunks.
134
135        Subclasses should return a valid ``UploadedFile`` object.
136        """
137        ...
138
139    def upload_complete(self) -> None:
140        """
141        Signal that the upload is complete. Subclasses should perform cleanup
142        that is necessary for this handler.
143        """
144
145    def upload_interrupted(self) -> None:
146        """
147        Signal that the upload was interrupted. Subclasses should perform
148        cleanup that is necessary for this handler.
149        """
150
151
152class TemporaryFileUploadHandler(FileUploadHandler):
153    """
154    Upload handler that streams data into a temporary file.
155    """
156
157    def new_file(self, *args: Any, **kwargs: Any) -> None:
158        """
159        Create the file object to append to as data is coming in.
160        """
161        super().new_file(*args, **kwargs)
162        assert self.file_name is not None, "file_name should be set by parent new_file"
163        assert self.content_type is not None, (
164            "content_type should be set by parent new_file"
165        )
166        self.file = TemporaryUploadedFile(
167            self.file_name, self.content_type, 0, self.charset, self.content_type_extra
168        )
169
170    def receive_data_chunk(self, raw_data: bytes, start: int) -> None:
171        self.file.write(raw_data)
172
173    def file_complete(self, file_size: int) -> TemporaryUploadedFile:
174        self.file.seek(0)
175        self.file.size = file_size
176        return self.file
177
178    def upload_interrupted(self) -> None:
179        if hasattr(self, "file"):
180            temp_location = self.file.temporary_file_path()
181            try:
182                self.file.close()
183                os.remove(temp_location)
184            except FileNotFoundError:
185                pass
186
187
188class MemoryFileUploadHandler(FileUploadHandler):
189    """
190    File upload handler to stream uploads into memory (used for small files).
191    """
192
193    def handle_raw_input(
194        self,
195        input_data: Any,
196        boundary: bytes,
197        encoding: str | None = None,
198    ) -> None:
199        """
200        Use the content_length to signal whether or not this handler should be
201        used.
202        """
203        # Check the content-length header to see if we should
204        # If the post is too large, we cannot use the Memory handler.
205        self.activated = (
206            self.request.content_length <= settings.FILE_UPLOAD_MAX_MEMORY_SIZE
207        )
208
209    def new_file(self, *args: Any, **kwargs: Any) -> None:
210        super().new_file(*args, **kwargs)
211        if self.activated:
212            self.file = BytesIO()
213            raise StopFutureHandlers()
214
215    def receive_data_chunk(self, raw_data: bytes, start: int) -> bytes | None:
216        """Add the data to the BytesIO file."""
217        if self.activated:
218            self.file.write(raw_data)
219            return None
220        else:
221            return raw_data
222
223    def file_complete(self, file_size: int) -> InMemoryUploadedFile | None:
224        """Return a file object if this handler is activated."""
225        if not self.activated:
226            return None
227
228        self.file.seek(0)
229        assert self.file_name is not None, "file_name should be set by new_file"
230        assert self.content_type is not None, "content_type should be set by new_file"
231        return InMemoryUploadedFile(
232            file=self.file,
233            field_name=self.field_name,
234            name=self.file_name,
235            content_type=self.content_type,
236            size=file_size,
237            charset=self.charset,
238            content_type_extra=self.content_type_extra,
239        )