diff options
| author | Andrew <saintruler@gmail.com> | 2019-07-07 23:40:09 +0400 |
|---|---|---|
| committer | Andrew <saintruler@gmail.com> | 2019-07-07 23:40:09 +0400 |
| commit | 5dc61e9d6a760e3a86b0bb459c0a628941069d95 (patch) | |
| tree | eeec35ae80b8befd2d2920d52cf08aa5bc695736 /day9/task5/utils.py | |
| parent | 64f9869d53bd4ec8b8867c8142a0deb919e143a4 (diff) | |
WIP: Добавлена загрузка файлов.
Diffstat (limited to 'day9/task5/utils.py')
| -rw-r--r-- | day9/task5/utils.py | 59 |
1 files changed, 58 insertions, 1 deletions
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 |