-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_response.py
More file actions
45 lines (37 loc) · 1.57 KB
/
Copy pathhttp_response.py
File metadata and controls
45 lines (37 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class HTTPResponse:
def __init__(self, response):
headers, content = response.split(b'\r\n\r\n', 1)
self.content = content
self.headers = {}
headers = headers.split(b'\r\n')
self.status = headers[0]
for header in headers[1:]:
key, value = header.split(b':', 1)
self.headers[key.strip().lower()] = value.strip()
def is_completed(self):
content_length = self.headers.get(b'content-length')
if content_length is not None and int(content_length) <= len(self.content):
return True
transfer_encoding = self.headers.get(b'transfer-encoding')
if transfer_encoding == b'chunked' and self.content.endswith(b'0\r\n\r\n'):
return True
return False
def add_content(self, content):
self.content += content
def print(self):
print(f'Статус ответа: \n{self.status.decode(errors='replace')}\n')
print(f'Заголовки:')
for key, value in self.headers.items():
print(f'{key.decode(errors='replace')}: {value.decode(errors='replace')}')
print(f'\nСодержание ответа: \n {self.content.decode(errors='replace')}')
def remove_chunk_encoding(self):
clear_content = b''
data = self.content
num, data = data.split(b'\r\n', 1)
num = int(num, 16)
while num != 0:
clear_content += data[:num]
data = data[num + 2:]
num, data = data.split(b'\r\n', 1)
num = int(num, 16)
self.content = clear_content