Skip to content

Commit 7cc1121

Browse files
committed
http: partial refectoring
1 parent 618bb44 commit 7cc1121

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

python/http.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,25 @@ def request(url):
2525
port = int(port)
2626

2727
# 4. Connect
28-
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) as s:
28+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) as sock:
2929
if scheme == "https":
3030
ctx = ssl.create_default_context()
31-
s = ctx.wrap_socket(s, server_hostname=host)
31+
with ctx.wrap_socket(sock, server_hostname=host) as ssock:
32+
return _get_headers_and_body(ssock, host, port, path)
33+
return _get_headers_and_body(sock, host, port, path)
3234

33-
s.connect((host, port))
3435

35-
# 5. Send request
36-
s.send(f"GET {path} HTTP/1.0\r\n".encode())
37-
s.send(f"Host: {host}\r\n".encode())
38-
s.send("Accept-Encoding: br,gzip,deflate\r\n".encode())
39-
s.send("\r\n".encode())
36+
def _get_headers_and_body(sock, host, port, path):
37+
sock.connect((host, port))
4038

41-
# 6. Receive response
42-
response = s.makefile("rb", newline="\r\n")
39+
# 5. Send request
40+
sock.send(f"GET {path} HTTP/1.0\r\n".encode())
41+
sock.send(f"Host: {host}\r\n".encode())
42+
sock.send("Accept-Encoding: br,gzip,deflate\r\n".encode())
43+
sock.send("\r\n".encode())
4344

45+
# 6. Receive response
46+
with sock.makefile("rb", newline="\r\n") as response:
4447
# 7. Read status line
4548
line = response.readline().decode()
4649
# 8. Parse status line
@@ -55,15 +58,16 @@ def request(url):
5558
line = response.readline().decode()
5659
if line == "\r\n":
5760
break
61+
5862
header, value = line.split(":", 1)
5963
headers[header.lower()] = value.strip()
6064

6165
body = response.read()
6266
if "content-encoding" in headers:
6367
encoding = headers["content-encoding"]
6468
body = decompress(body, encoding)
65-
body = body.decode()
6669

70+
body = body.decode()
6771
# 12. Return
6872
return headers, body
6973

0 commit comments

Comments
 (0)