multipart-decoder 0.0.0.dev0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Satya Tulasi Jalandhar C H
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: multipart-decoder
3
+ Version: 0.0.0.dev0
4
+ Summary: A lightweight Python package for parsing multipart/form-data content
5
+ Author-email: Satya Tulasi Jalandhar C H <satyatulasijalandharch2@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/satyatulasijalandharch/multipart-decoder
8
+ Project-URL: Issues, https://github.com/satyatulasijalandharch/multipart-decoder/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests_toolbelt==1.0.0
15
+ Dynamic: license-file
16
+
17
+ # multipart_decoder
18
+
19
+ A lightweight Python package for parsing multipart/form-data content.
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install multipart-decoder
25
+ ```
26
+
27
+
28
+ **Basic Usage Example for multipart_decoder**
29
+
30
+ This example demonstrates how to parse simple form data with text fields.
31
+
32
+ ```python
33
+
34
+ from multipart_decoder import MultipartFormParser
35
+
36
+ # Example with raw form data
37
+ def basic_form_parsing():
38
+ # In a real application, these would come from an HTTP request
39
+ content_type = "multipart/form-data; boundary=----WebKitFormBoundarydVTl2EAp1scXYsWZ"
40
+ body = "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5ZFZUbDJFQXAxc2NYWXNXWg0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJ1c2VybmFtZSINCg0KZXhhbXBsZV91c2VyDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnlkVlRsMkVBcDFzY1hZc1daDQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImVtYWlsIg0KDQp1c2VyQGV4YW1wbGUuY29tDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnlkVlRsMkVBcDFzY1hZc1daLS0NCg=="
41
+
42
+ # Parse the multipart form data
43
+ form_data = MultipartFormParser(body, content_type)
44
+
45
+ # Access the form fields
46
+ print(f"Username: {form_data['fields']['username']}")
47
+ print(f"Email: {form_data['fields']['email']}")
48
+
49
+ # Show the entire parsed data structure
50
+ print("\nComplete form data dictionary:")
51
+ print(form_data)
52
+
53
+ if __name__ == "__main__":
54
+ basic_form_parsing()
55
+
56
+ ```
57
+ ## Expected Output
58
+
59
+ ### Basic Form Parsing:
60
+ - **Username**: `example_user`
61
+ - **Email**: `user@example.com`
62
+
63
+ #### Complete Form Data Dictionary:
64
+ ```json
65
+ {
66
+ "fields": {
67
+ "username": "example_user",
68
+ "email": "user@example.com"
69
+ },
70
+ "files": {}
71
+ }
72
+
73
+ ```
74
+
75
+
76
+ **File Upload Example for multipart_decoder**
77
+
78
+ This example demonstrates how to handle file uploads in multipart form data.
79
+
80
+ ```python
81
+ from multipart_decoder import MultipartFormParser
82
+ import os
83
+
84
+ def process_file_upload():
85
+ content_type = "multipart/form-data; boundary=----WebKitFormBoundary4AQwYOUUCEUw9hsX"
86
+ body = "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDEiDQoNCnZhbHVlMQ0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDIiDQoNCnZhbHVlMg0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlMSI7IGZpbGVuYW1lPSJleGFtcGxlLnR4dCINCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KDQpIZWxsbywgd29ybGQhDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnk0QVF3WU9VVUNFVXc5aHNYLS0NCg=="
87
+
88
+ form_data = MultipartFormParser(body, content_type)
89
+
90
+ # Access fields
91
+ print(f"Field 1: {form_data['fields']['field1']}")
92
+ print(f"Field 2: {form_data['fields']['field2']}")
93
+
94
+ # Access files
95
+ if 'file1' in form_data['files']:
96
+ file_info = form_data['files']['file1']
97
+ print(f" - Filename: {file_info['filename']}")
98
+ print(f" - Content type: {file_info['content_type']}")
99
+ print(f" - File size: {file_info['size']} bytes")
100
+
101
+ # Example: save the file
102
+ save_path = f"saved_{file_info['filename']}"
103
+ with open(save_path, "wb") as f:
104
+ f.write(file_info['content'])
105
+ print(f" - File saved to: {save_path}")
106
+
107
+ # Cleanup (for demonstration)
108
+ os.remove(save_path)
109
+
110
+ if __name__ == "__main__":
111
+ process_file_upload()
112
+
113
+ ```
114
+ # Expected Output:
115
+
116
+ ### Test Fields:
117
+ - **Field 1**: `value1`
118
+ - **Field 2**: `value2`
119
+
120
+ ### File Field:
121
+ - **Filename**: `example.txt`
122
+ - **Content Type**: `text/plain`
123
+ - **File Size**: `13 bytes`
124
+ - **File Saved To**: `saved_example.txt`
@@ -0,0 +1,108 @@
1
+ # multipart_decoder
2
+
3
+ A lightweight Python package for parsing multipart/form-data content.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install multipart-decoder
9
+ ```
10
+
11
+
12
+ **Basic Usage Example for multipart_decoder**
13
+
14
+ This example demonstrates how to parse simple form data with text fields.
15
+
16
+ ```python
17
+
18
+ from multipart_decoder import MultipartFormParser
19
+
20
+ # Example with raw form data
21
+ def basic_form_parsing():
22
+ # In a real application, these would come from an HTTP request
23
+ content_type = "multipart/form-data; boundary=----WebKitFormBoundarydVTl2EAp1scXYsWZ"
24
+ body = "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5ZFZUbDJFQXAxc2NYWXNXWg0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJ1c2VybmFtZSINCg0KZXhhbXBsZV91c2VyDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnlkVlRsMkVBcDFzY1hZc1daDQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImVtYWlsIg0KDQp1c2VyQGV4YW1wbGUuY29tDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnlkVlRsMkVBcDFzY1hZc1daLS0NCg=="
25
+
26
+ # Parse the multipart form data
27
+ form_data = MultipartFormParser(body, content_type)
28
+
29
+ # Access the form fields
30
+ print(f"Username: {form_data['fields']['username']}")
31
+ print(f"Email: {form_data['fields']['email']}")
32
+
33
+ # Show the entire parsed data structure
34
+ print("\nComplete form data dictionary:")
35
+ print(form_data)
36
+
37
+ if __name__ == "__main__":
38
+ basic_form_parsing()
39
+
40
+ ```
41
+ ## Expected Output
42
+
43
+ ### Basic Form Parsing:
44
+ - **Username**: `example_user`
45
+ - **Email**: `user@example.com`
46
+
47
+ #### Complete Form Data Dictionary:
48
+ ```json
49
+ {
50
+ "fields": {
51
+ "username": "example_user",
52
+ "email": "user@example.com"
53
+ },
54
+ "files": {}
55
+ }
56
+
57
+ ```
58
+
59
+
60
+ **File Upload Example for multipart_decoder**
61
+
62
+ This example demonstrates how to handle file uploads in multipart form data.
63
+
64
+ ```python
65
+ from multipart_decoder import MultipartFormParser
66
+ import os
67
+
68
+ def process_file_upload():
69
+ content_type = "multipart/form-data; boundary=----WebKitFormBoundary4AQwYOUUCEUw9hsX"
70
+ body = "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDEiDQoNCnZhbHVlMQ0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDIiDQoNCnZhbHVlMg0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlMSI7IGZpbGVuYW1lPSJleGFtcGxlLnR4dCINCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KDQpIZWxsbywgd29ybGQhDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnk0QVF3WU9VVUNFVXc5aHNYLS0NCg=="
71
+
72
+ form_data = MultipartFormParser(body, content_type)
73
+
74
+ # Access fields
75
+ print(f"Field 1: {form_data['fields']['field1']}")
76
+ print(f"Field 2: {form_data['fields']['field2']}")
77
+
78
+ # Access files
79
+ if 'file1' in form_data['files']:
80
+ file_info = form_data['files']['file1']
81
+ print(f" - Filename: {file_info['filename']}")
82
+ print(f" - Content type: {file_info['content_type']}")
83
+ print(f" - File size: {file_info['size']} bytes")
84
+
85
+ # Example: save the file
86
+ save_path = f"saved_{file_info['filename']}"
87
+ with open(save_path, "wb") as f:
88
+ f.write(file_info['content'])
89
+ print(f" - File saved to: {save_path}")
90
+
91
+ # Cleanup (for demonstration)
92
+ os.remove(save_path)
93
+
94
+ if __name__ == "__main__":
95
+ process_file_upload()
96
+
97
+ ```
98
+ # Expected Output:
99
+
100
+ ### Test Fields:
101
+ - **Field 1**: `value1`
102
+ - **Field 2**: `value2`
103
+
104
+ ### File Field:
105
+ - **Filename**: `example.txt`
106
+ - **Content Type**: `text/plain`
107
+ - **File Size**: `13 bytes`
108
+ - **File Saved To**: `saved_example.txt`
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "multipart-decoder"
7
+ version = "0.0.0.dev0"
8
+ authors = [
9
+ { name="Satya Tulasi Jalandhar C H", email="satyatulasijalandharch2@gmail.com" },
10
+ ]
11
+ description = "A lightweight Python package for parsing multipart/form-data content"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ dependencies = [
15
+ "requests_toolbelt==1.0.0"
16
+ ]
17
+ classifiers = [
18
+ "Programming Language :: Python :: 3",
19
+ "Operating System :: OS Independent",
20
+ ]
21
+ license = "MIT"
22
+ license-files = ["LICENSE*"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/satyatulasijalandharch/multipart-decoder"
26
+ Issues = "https://github.com/satyatulasijalandharch/multipart-decoder/issues"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,8 @@
1
+ """
2
+ multipart_decoder - A lightweight Python package for parsing multipart/form-data content.
3
+ """
4
+
5
+ from .decoder import MultipartFormParser
6
+
7
+ __version__ = "0.0.1"
8
+ __all__ = ["MultipartFormParser"]
@@ -0,0 +1,95 @@
1
+ """
2
+ Decoder module for parsing multipart/form-data content.
3
+ """
4
+
5
+ import re
6
+ import logging
7
+ from base64 import b64decode
8
+ from binascii import Error as BinasciiError
9
+ from requests_toolbelt.multipart import decoder
10
+
11
+
12
+ def MultipartFormParser(body, content_type):
13
+ """
14
+ Decode a multipart/form-data request body.
15
+ :param body: The body of the request, typically a byte string.
16
+ :param content_type: The content type of the request, typically 'multipart/form-data; boundary=...'.
17
+ :return: A dictionary containing the extracted fields and files.
18
+ :raises ValueError: If input parameters are invalid
19
+ :raises Exception: For various parsing errors
20
+ """
21
+ extracted_data = {"fields": {}, "files": {}}
22
+
23
+ # Validate input parameters
24
+ if not body:
25
+ raise ValueError("Request body cannot be empty")
26
+ if not content_type or 'boundary=' not in content_type:
27
+ raise ValueError("Invalid content type: must be multipart/form-data with boundary")
28
+
29
+ try:
30
+ # Decode the base64 encoded body
31
+ try:
32
+ data = b64decode(body)
33
+ except BinasciiError as e:
34
+ raise ValueError(f"Invalid base64 encoded body: {str(e)}")
35
+
36
+ # Parse multipart data
37
+ try:
38
+ multipart_data = decoder.MultipartDecoder(data, content_type)
39
+ except Exception as e:
40
+ raise ValueError(f"Failed to decode multipart form data: {str(e)}")
41
+
42
+ # Process parts
43
+ for part in multipart_data.parts:
44
+ try:
45
+ # Get content disposition header
46
+ if b"Content-Disposition" not in part.headers:
47
+ logging.warning("Skipping part without Content-Disposition header")
48
+ continue
49
+
50
+ content_disposition = part.headers[b"Content-Disposition"].decode()
51
+
52
+ # Extract the field name
53
+ name_match = re.search(r'name="([^"]+)"', content_disposition)
54
+ if not name_match:
55
+ logging.warning("Skipping part without field name")
56
+ continue
57
+
58
+ field_name = name_match.group(1)
59
+
60
+ # Check if it's a file
61
+ filename_match = re.search(r'filename="([^"]+)"', content_disposition)
62
+
63
+ if filename_match:
64
+ # Handle file upload
65
+ filename = filename_match.group(1)
66
+ content_type = part.headers.get(
67
+ b"Content-Type", b"application/octet-stream"
68
+ ).decode()
69
+ file_data = part.content
70
+
71
+ # Store file information
72
+ extracted_data["files"][field_name] = {
73
+ "filename": filename,
74
+ "content_type": content_type,
75
+ "content": file_data,
76
+ "size": len(file_data),
77
+ }
78
+ else:
79
+ # Handle regular form fields
80
+ try:
81
+ field_value = part.text.strip()
82
+ except UnicodeDecodeError:
83
+ logging.warning(f"Could not decode text for field {field_name}, storing as binary")
84
+ field_value = part.content
85
+ extracted_data["fields"][field_name] = field_value
86
+
87
+ except Exception as e:
88
+ logging.error(f"Error processing part: {str(e)}")
89
+ # Continue processing other parts instead of failing completely
90
+
91
+ except Exception as e:
92
+ # Re-raise with more context
93
+ raise Exception(f"Failed to parse multipart form data: {str(e)}") from e
94
+
95
+ return extracted_data
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: multipart-decoder
3
+ Version: 0.0.0.dev0
4
+ Summary: A lightweight Python package for parsing multipart/form-data content
5
+ Author-email: Satya Tulasi Jalandhar C H <satyatulasijalandharch2@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/satyatulasijalandharch/multipart-decoder
8
+ Project-URL: Issues, https://github.com/satyatulasijalandharch/multipart-decoder/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests_toolbelt==1.0.0
15
+ Dynamic: license-file
16
+
17
+ # multipart_decoder
18
+
19
+ A lightweight Python package for parsing multipart/form-data content.
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install multipart-decoder
25
+ ```
26
+
27
+
28
+ **Basic Usage Example for multipart_decoder**
29
+
30
+ This example demonstrates how to parse simple form data with text fields.
31
+
32
+ ```python
33
+
34
+ from multipart_decoder import MultipartFormParser
35
+
36
+ # Example with raw form data
37
+ def basic_form_parsing():
38
+ # In a real application, these would come from an HTTP request
39
+ content_type = "multipart/form-data; boundary=----WebKitFormBoundarydVTl2EAp1scXYsWZ"
40
+ body = "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5ZFZUbDJFQXAxc2NYWXNXWg0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJ1c2VybmFtZSINCg0KZXhhbXBsZV91c2VyDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnlkVlRsMkVBcDFzY1hZc1daDQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImVtYWlsIg0KDQp1c2VyQGV4YW1wbGUuY29tDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnlkVlRsMkVBcDFzY1hZc1daLS0NCg=="
41
+
42
+ # Parse the multipart form data
43
+ form_data = MultipartFormParser(body, content_type)
44
+
45
+ # Access the form fields
46
+ print(f"Username: {form_data['fields']['username']}")
47
+ print(f"Email: {form_data['fields']['email']}")
48
+
49
+ # Show the entire parsed data structure
50
+ print("\nComplete form data dictionary:")
51
+ print(form_data)
52
+
53
+ if __name__ == "__main__":
54
+ basic_form_parsing()
55
+
56
+ ```
57
+ ## Expected Output
58
+
59
+ ### Basic Form Parsing:
60
+ - **Username**: `example_user`
61
+ - **Email**: `user@example.com`
62
+
63
+ #### Complete Form Data Dictionary:
64
+ ```json
65
+ {
66
+ "fields": {
67
+ "username": "example_user",
68
+ "email": "user@example.com"
69
+ },
70
+ "files": {}
71
+ }
72
+
73
+ ```
74
+
75
+
76
+ **File Upload Example for multipart_decoder**
77
+
78
+ This example demonstrates how to handle file uploads in multipart form data.
79
+
80
+ ```python
81
+ from multipart_decoder import MultipartFormParser
82
+ import os
83
+
84
+ def process_file_upload():
85
+ content_type = "multipart/form-data; boundary=----WebKitFormBoundary4AQwYOUUCEUw9hsX"
86
+ body = "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDEiDQoNCnZhbHVlMQ0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDIiDQoNCnZhbHVlMg0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlMSI7IGZpbGVuYW1lPSJleGFtcGxlLnR4dCINCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KDQpIZWxsbywgd29ybGQhDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnk0QVF3WU9VVUNFVXc5aHNYLS0NCg=="
87
+
88
+ form_data = MultipartFormParser(body, content_type)
89
+
90
+ # Access fields
91
+ print(f"Field 1: {form_data['fields']['field1']}")
92
+ print(f"Field 2: {form_data['fields']['field2']}")
93
+
94
+ # Access files
95
+ if 'file1' in form_data['files']:
96
+ file_info = form_data['files']['file1']
97
+ print(f" - Filename: {file_info['filename']}")
98
+ print(f" - Content type: {file_info['content_type']}")
99
+ print(f" - File size: {file_info['size']} bytes")
100
+
101
+ # Example: save the file
102
+ save_path = f"saved_{file_info['filename']}"
103
+ with open(save_path, "wb") as f:
104
+ f.write(file_info['content'])
105
+ print(f" - File saved to: {save_path}")
106
+
107
+ # Cleanup (for demonstration)
108
+ os.remove(save_path)
109
+
110
+ if __name__ == "__main__":
111
+ process_file_upload()
112
+
113
+ ```
114
+ # Expected Output:
115
+
116
+ ### Test Fields:
117
+ - **Field 1**: `value1`
118
+ - **Field 2**: `value2`
119
+
120
+ ### File Field:
121
+ - **Filename**: `example.txt`
122
+ - **Content Type**: `text/plain`
123
+ - **File Size**: `13 bytes`
124
+ - **File Saved To**: `saved_example.txt`
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/multipart_decoder/__init__.py
5
+ src/multipart_decoder/decoder.py
6
+ src/multipart_decoder.egg-info/PKG-INFO
7
+ src/multipart_decoder.egg-info/SOURCES.txt
8
+ src/multipart_decoder.egg-info/dependency_links.txt
9
+ src/multipart_decoder.egg-info/requires.txt
10
+ src/multipart_decoder.egg-info/top_level.txt
11
+ tests/test_decoder.py
@@ -0,0 +1 @@
1
+ requests_toolbelt==1.0.0
@@ -0,0 +1,75 @@
1
+ """
2
+ Unit tests for the multipart_decoder package.
3
+ """
4
+
5
+ import unittest
6
+ from multipart_decoder import MultipartFormParser
7
+
8
+
9
+ class TestMultipartFormParser(unittest.TestCase):
10
+ def test_basic_form_fields(self):
11
+ """Test decoding of basic form fields."""
12
+ content_type = (
13
+ "multipart/form-data; boundary=----WebKitFormBoundaryp0mBfJEEcQtmxFCF"
14
+ )
15
+ body = "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5cDBtQmZKRUVjUXRteEZDRg0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDEiDQoNCnZhbHVlMQ0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5cDBtQmZKRUVjUXRteEZDRg0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDIiDQoNCnZhbHVlMg0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5cDBtQmZKRUVjUXRteEZDRi0tDQo="
16
+
17
+ result = MultipartFormParser(body, content_type)
18
+ self.assertEqual(result["fields"]["field1"], "value1")
19
+ self.assertEqual(result["fields"]["field2"], "value2")
20
+
21
+ def test_file_upload(self):
22
+ """Test decoding of file uploads."""
23
+ content_type = (
24
+ "multipart/form-data; boundary=----WebKitFormBoundaryI6YbOCiSAMjU6wK2"
25
+ )
26
+ body = "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5STZZYk9DaVNBTWpVNndLMg0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlMSI7IGZpbGVuYW1lPSJleGFtcGxlLnR4dCINCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KDQpIZWxsbywgd29ybGQhDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnlJNlliT0NpU0FNalU2d0syLS0NCg=="
27
+
28
+ result = MultipartFormParser(body, content_type)
29
+ self.assertIn("file1", result["files"])
30
+
31
+ file_info = result["files"]["file1"]
32
+ self.assertEqual(file_info["filename"], "example.txt")
33
+ self.assertEqual(file_info["content_type"], "text/plain")
34
+ self.assertEqual(file_info["content"], b"Hello, world!")
35
+ self.assertEqual(file_info["size"], len(b"Hello, world!"))
36
+
37
+ def test_mixed_content(self):
38
+ """Test decoding of mixed content (form fields and file uploads)."""
39
+ content_type = (
40
+ "multipart/form-data; boundary=----WebKitFormBoundary4AQwYOUUCEUw9hsX"
41
+ )
42
+ body = "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDEiDQoNCnZhbHVlMQ0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWVsZDIiDQoNCnZhbHVlMg0KLS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5NEFRd1lPVVVDRVV3OWhzWA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlMSI7IGZpbGVuYW1lPSJleGFtcGxlLnR4dCINCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KDQpIZWxsbywgd29ybGQhDQotLS0tLS1XZWJLaXRGb3JtQm91bmRhcnk0QVF3WU9VVUNFVXc5aHNYLS0NCg=="
43
+
44
+ result = MultipartFormParser(body, content_type)
45
+ self.assertEqual(result["fields"]["field1"], "value1")
46
+ self.assertEqual(result["fields"]["field2"], "value2")
47
+
48
+ file_info = result["files"]["file1"]
49
+ self.assertEqual(file_info["filename"], "example.txt")
50
+ self.assertEqual(file_info["content_type"], "text/plain")
51
+ self.assertEqual(file_info["content"], b"Hello, world!")
52
+ self.assertEqual(file_info["size"], len(b"Hello, world!"))
53
+
54
+ def test_empty_body(self):
55
+ """Test validation of empty request body."""
56
+ content_type = "multipart/form-data; boundary=something"
57
+ body = ""
58
+
59
+ with self.assertRaises(ValueError) as context:
60
+ MultipartFormParser(body, content_type)
61
+ self.assertIn("Request body cannot be empty", str(context.exception))
62
+
63
+ def test_malformed_multipart_data(self):
64
+ """Test handling of malformed multipart data."""
65
+ content_type = "multipart/form-data; boundary=boundary"
66
+ # Base64 encoded partial/malformed multipart data
67
+ body = "LS0tYm91bmRhcnkNCkNvbnRlbnQtRGlzcG9zaXRpb246IGZvcm0tZGF0YTsNCg=="
68
+
69
+ with self.assertRaises(Exception) as context:
70
+ MultipartFormParser(body, content_type)
71
+ self.assertIn("Failed to", str(context.exception))
72
+
73
+
74
+ if __name__ == "__main__":
75
+ unittest.main()