multipart-decoder 0.0.0.dev0__py3-none-any.whl
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.
- multipart_decoder/__init__.py +8 -0
- multipart_decoder/decoder.py +95 -0
- multipart_decoder-0.0.0.dev0.dist-info/METADATA +124 -0
- multipart_decoder-0.0.0.dev0.dist-info/RECORD +7 -0
- multipart_decoder-0.0.0.dev0.dist-info/WHEEL +5 -0
- multipart_decoder-0.0.0.dev0.dist-info/licenses/LICENSE +9 -0
- multipart_decoder-0.0.0.dev0.dist-info/top_level.txt +1 -0
|
@@ -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,7 @@
|
|
|
1
|
+
multipart_decoder/__init__.py,sha256=tiuyR-FP5dUjByf_LZBHkam9knw_oQP9mzzMKjotglg,205
|
|
2
|
+
multipart_decoder/decoder.py,sha256=To6JKE4idbGLpY8kdIxNf1NUeJ0IotcAo4ppo3mc98M,3942
|
|
3
|
+
multipart_decoder-0.0.0.dev0.dist-info/licenses/LICENSE,sha256=PyOuOqZTD-R_FU1uhZIEePbnzVqsJA0acIYS99d_aCQ,1098
|
|
4
|
+
multipart_decoder-0.0.0.dev0.dist-info/METADATA,sha256=9SfuK8l1A3NsUoqjCdYwscGPEN-wVby2po2FawSDFCo,4283
|
|
5
|
+
multipart_decoder-0.0.0.dev0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
|
6
|
+
multipart_decoder-0.0.0.dev0.dist-info/top_level.txt,sha256=WA7TLPdXiS3PDIHgyhYIpW6uuf_QoPtfiFejnd7hJeQ,18
|
|
7
|
+
multipart_decoder-0.0.0.dev0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
multipart_decoder
|