From 5dc61e9d6a760e3a86b0bb459c0a628941069d95 Mon Sep 17 00:00:00 2001 From: Andrew Date: Sun, 7 Jul 2019 23:40:09 +0400 Subject: =?UTF-8?q?WIP:=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=B7=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=BA=D0=B0=20?= =?UTF-8?q?=D1=84=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day9/task5/utils.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) (limited to 'day9/task5/utils.py') diff --git a/day9/task5/utils.py b/day9/task5/utils.py index 3e0dc64..8f3e794 100644 --- a/day9/task5/utils.py +++ b/day9/task5/utils.py @@ -1,4 +1,7 @@ -import re +from io import BytesIO + + +CHUNK_SIZE = 49600 HTTP_STATUS_CODES = { 100: "Continue", @@ -74,3 +77,57 @@ def render_template(path, **kwargs): template = template.replace(f'%%{key}%%', kwargs[key]) return template + + +def parse_multipart_form(data: bytes): + b = BytesIO(data) + separator = b.readline().strip() + + files = [] + with open('request', 'wb') as f: + f.write(data) + + while True: + line = b.readline().strip().strip(b'-') + if not line: + break + + headers_raw = [] + while not line.strip() == b'': + headers_raw.append(line.strip().decode()) + line = b.readline() + + headers = {'Content-Type': headers_raw[1].split(': ')[1]} + for pair in headers_raw[0].split(': ')[1].split('; ')[1:]: + key, value = pair.split('=') + headers[key] = value[1:-1] + + data = b'' + prev_chunk = b.read(CHUNK_SIZE) + chunk = b.read(CHUNK_SIZE) + while separator not in (prev_chunk + chunk): + data += prev_chunk + prev_chunk = chunk + chunk = b.read(CHUNK_SIZE) + + if not chunk: + break + + chunk = (prev_chunk + chunk) + if chunk.startswith(separator) or chunk.endswith(separator): + with_sep = chunk.strip(separator) + else: + if separator in chunk: + with_sep, buffer = chunk.split(separator) + b = BytesIO(buffer + b.read()) + b.readline() + + else: + with_sep = chunk + + data += with_sep + headers['data'] = data + + files.append(headers) + + return files -- cgit v1.2.3