Created
June 5, 2019 00:53
-
-
Save ctkirkman/0c6a21bd10f4decb0abd62f17a61e5fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pathlib | |
import cgi | |
def parse_multipart(data, headers): | |
result = list() | |
content_type, options = cgi.parse_header(headers.get("Content-Type")) | |
if options.get("boundary") is not None: | |
result = data.split(b"--" + options.get("boundary").encode()) | |
for r in result[1:]: | |
parts = r.split(b"\r\n\r\n", 1) | |
preamble = parts[0].strip(b"\r\n").split(b"\r\n") | |
if preamble[0] == b"--": | |
break | |
else: | |
content_disposition, preamble_options = cgi.parse_header(preamble[0].decode(errors="ignore")) | |
if len(preamble) > 1: | |
for pre in preamble[1:]: | |
# print(pre) | |
pass | |
if len(parts) == 2: | |
if preamble_options.get("filename", "") != "": | |
# print(preamble_options) | |
# print(preamble_options.get("filename")) | |
# with open(f"/tmp/{preamble_options.get('filename')}", "wb") as out_f: | |
# out_f.write(parts[1]) | |
pass | |
else: | |
pass | |
# print(parts[1][:100]) | |
elif len(parts) < 2: | |
raise RuntimeError(f"Components In Boundary Less Than Expected:\r\n{str(parts)[:100]}") | |
else: | |
raise RuntimeError(f"Components In Boundary Greater Than Expected:\r\n{str(parts)[:100]}") | |
else: | |
raise RuntimeError("Boundary Not Defined") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment