Debian Codegraph @

tests/file_uploads/uploadhandler.py

raw
1 """
2 Upload handlers to test the upload API.
3 """
4
5 import os
6 from tempfile import NamedTemporaryFile
7
8 from django.core.files.uploadhandler import (
9 FileUploadHandler,
10 StopUpload,
11 TemporaryFileUploadHandler,
12 )
13
14
15 class QuotaUploadHandler(FileUploadHandler):
16 """
17 This test upload handler terminates the connection if more than a quota
18 (5MB) is uploaded.
19 """
20
21 QUOTA = 5 * 2**20 # 5 MB
22
23 def __init__(self, request=None):
24 super().__init__(request)
25 self.total_upload = 0
26
27 def receive_data_chunk(self, raw_data, start):
28 self.total_upload += len(raw_data)
29 if self.total_upload >= self.QUOTA:
30 raise StopUpload(connection_reset=True)
31 return raw_data
32
33 def file_complete(self, file_size):
34 return None
35
36
37 class StopUploadTemporaryFileHandler(TemporaryFileUploadHandler):
38 """A handler that raises a StopUpload exception."""
39
40 def receive_data_chunk(self, raw_data, start):
41 raise StopUpload()
42
43
44 class CustomUploadError(Exception):
45 pass
46
47
48 class ErroringUploadHandler(FileUploadHandler):
49 """A handler that raises an exception."""
50
51 def receive_data_chunk(self, raw_data, start):
52 raise CustomUploadError("Oops!")
53
54
55 class TraversalUploadHandler(FileUploadHandler):
56 """A handler with potential directory-traversal vulnerability."""
57
58 def __init__(self, request=None):
59 from .tests import UPLOAD_TO
60
61 super().__init__(request)
62 self.upload_dir = UPLOAD_TO
63
64 def file_complete(self, file_size):
65 self.file.seek(0)
66 self.file.size = file_size
67 with open(os.path.join(self.upload_dir, self.file_name), "wb") as fp:
68 fp.write(self.file.read())
69 return self.file
70
71 def new_file(
72 self,
73 field_name,
74 file_name,
75 content_type,
76 content_length,
77 charset=None,
78 content_type_extra=None,
79 ):
80 super().new_file(
81 file_name,
82 file_name,
83 content_length,
84 content_length,
85 charset,
86 content_type_extra,
87 )
88 self.file = NamedTemporaryFile(suffix=".upload", dir=self.upload_dir)
89
90 def receive_data_chunk(self, raw_data, start):
91 self.file.write(raw_data)