Skip to content

Commit 3790fd6

Browse files
committed
Refactoring. Using black code style
1 parent 72ae3c2 commit 3790fd6

8 files changed

+70
-53
lines changed

socket__tcp__examples/common.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
# SOURCE: https://stackoverflow.com/a/17668009/5909792
88

99

1010
import struct
1111
import zlib
12-
from typing import Optional
1312

1413

1514
def crc32_from_bytes(data: bytes) -> int:
@@ -19,12 +18,12 @@ def crc32_from_bytes(data: bytes) -> int:
1918
def send_msg__with_crc32(sock, msg):
2019
# Prefix each message with a 12-byte (network byte order) length: 8-byte data length and 4-byte crc32 data
2120
crc32 = crc32_from_bytes(msg)
22-
msg = struct.pack('>QI', len(msg), crc32) + msg
21+
msg = struct.pack(">QI", len(msg), crc32) + msg
2322

2423
sock.sendall(msg)
2524

2625

27-
def recv_msg__with_crc32(sock) -> Optional[bytes]:
26+
def recv_msg__with_crc32(sock) -> bytes | None:
2827
# 12-byte
2928
payload_size = struct.calcsize(">QI")
3029

@@ -33,26 +32,30 @@ def recv_msg__with_crc32(sock) -> Optional[bytes]:
3332
if not raw_msg_len:
3433
return None
3534

36-
msg_len, crc32 = struct.unpack('>QI', raw_msg_len)
35+
msg_len, crc32 = struct.unpack(">QI", raw_msg_len)
3736

3837
# Read the message data
3938
msg = recv_all(sock, msg_len)
4039

4140
# Check message
4241
msg_crc32 = crc32_from_bytes(msg)
4342
if msg_crc32 != crc32:
44-
raise Exception('Incorrect message: invalid crc32. Receiving crc32: {}, current: {}'.format(crc32, msg_crc32))
43+
raise Exception(
44+
"Incorrect message: invalid crc32. Receiving crc32: {}, current: {}".format(
45+
crc32, msg_crc32
46+
)
47+
)
4548

4649
return msg
4750

4851

4952
def send_msg(sock, msg):
5053
# Prefix each message with a 8-byte length (network byte order)
51-
msg = struct.pack('>Q', len(msg)) + msg
54+
msg = struct.pack(">Q", len(msg)) + msg
5255
sock.sendall(msg)
5356

5457

55-
def recv_msg(sock) -> Optional[bytes]:
58+
def recv_msg(sock) -> bytes | None:
5659
# 8-byte
5760
payload_size = struct.calcsize(">Q")
5861

@@ -61,13 +64,13 @@ def recv_msg(sock) -> Optional[bytes]:
6164
if not raw_msg_len:
6265
return None
6366

64-
msg_len = struct.unpack('>Q', raw_msg_len)[0]
67+
msg_len = struct.unpack(">Q", raw_msg_len)[0]
6568

6669
# Read the message data
6770
return recv_all(sock, msg_len)
6871

6972

70-
def recv_all(sock, n) -> Optional[bytes]:
73+
def recv_all(sock, n) -> bytes | None:
7174
# Helper function to recv n bytes or return None if EOF is hit
7275
data = bytearray()
7376

socket__tcp__examples/http__get.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
5+
6+
7+
import socket
58

69

710
request = b"GET / HTTP/1.1\nHost: stackoverflow.com\n\n"
811
host = "stackoverflow.com"
912
port = 80
1013

11-
import socket
1214
sock = socket.socket()
1315
sock.settimeout(60) # Если за 60 секунд данные не придут, соединение закрывается
1416
sock.connect((host, port))

socket__tcp__examples/http__get__via_proxy.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
# SOURCE: http://stackoverflow.com/a/42913875/5909792
88
# Connect to proxy, in http request write full host address
99

10+
11+
import socket
12+
13+
1014
BUFFER_SIZE = 1024
1115

1216
request = b"GET http://stackoverflow.com HTTP/1.1\nHost: stackoverflow.com\n\n"
1317
host = "proxy.compassplus.ru"
1418
port = 3128
1519

16-
import socket
1720
sock = socket.socket()
1821
sock.settimeout(60) # Если за 60 секунд данные не придут, соединение закрывается
1922

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

7-
from urllib.parse import urlsplit
87
import socket
98
import re
109

10+
from urllib.parse import urlsplit
11+
12+
1113
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1214
# url = input ("Enter a url: ")
13-
url = 'http://google.ru/'
15+
url = "http://google.ru/"
1416
try:
15-
re.search("^http[s]?://.*?", url)
17+
re.search("^https?://.*?", url)
1618
except:
1719
print("Error")
1820

@@ -21,14 +23,14 @@
2123

2224
socket.connect((result.netloc, 80))
2325

24-
cmd = f'GET {result.path} HTTP/1.0\r\n\r\n'.encode()
26+
cmd = f"GET {result.path} HTTP/1.0\r\n\r\n".encode()
2527
print(cmd)
2628
socket.send(cmd)
2729

2830
while True:
2931
data = socket.recv(512)
3032
if not len(data):
3133
break
32-
print(data, end='')
34+
print(data, end="")
3335

3436
socket.close()

socket__tcp__examples/http__post__contact_ng_server.py

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

7-
INT_SOFT_ID = '<INT_SOFT_ID>'
8-
POINT_CODE = '<POINT_CODE>'
7+
import socket
8+
9+
10+
INT_SOFT_ID = "<INT_SOFT_ID>"
11+
POINT_CODE = "<POINT_CODE>"
912

1013
# NG Server
1114
HOST = "10.7.8.31"
@@ -20,40 +23,41 @@
2023
SignOut="No"
2124
ExpectSigned="No"
2225
/>
23-
""".format(INT_SOFT_ID=INT_SOFT_ID, POINT_CODE=POINT_CODE)
26+
""".format(
27+
INT_SOFT_ID=INT_SOFT_ID, POINT_CODE=POINT_CODE
28+
)
2429

2530

2631
http_request = (
27-
'POST / HTTP/1.1\r\n',
28-
'Host: {host}:{port}\r\n',
29-
'Accept-Encoding: gzip, deflate\r\n',
30-
'User-Agent: {user_agent}\r\n',
31-
'Connection: keep-alive\r\n',
32-
'Accept: */*\r\n',
33-
'Content-Length: {content_length}\r\n',
34-
'\r\n',
35-
'\n',
36-
'{body}\n'
32+
"POST / HTTP/1.1\r\n",
33+
"Host: {host}:{port}\r\n",
34+
"Accept-Encoding: gzip, deflate\r\n",
35+
"User-Agent: {user_agent}\r\n",
36+
"Connection: keep-alive\r\n",
37+
"Accept: */*\r\n",
38+
"Content-Length: {content_length}\r\n",
39+
"\r\n",
40+
"\n",
41+
"{body}\n",
3742
)
38-
http_request = ''.join(http_request)
43+
http_request = "".join(http_request)
3944
http_request = http_request.format(
4045
host=HOST,
4146
port=PORT,
42-
user_agent='iHuman',
47+
user_agent="iHuman",
4348
content_length=len(post_data),
4449
body=post_data,
4550
)
4651

4752
print(repr(http_request))
4853

4954

50-
import socket
5155
sock = socket.socket()
5256
sock.connect((HOST, PORT))
5357
sock.send(http_request.encode())
5458

55-
print('Socket name: {}'.format(sock.getsockname()))
56-
print('\nResponse:')
59+
print("Socket name: {}".format(sock.getsockname()))
60+
print("\nResponse:")
5761

5862
while True:
5963
data = sock.recv(1024)

socket__tcp__examples/http_server.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
# SOURCE: http://andreymal.org/socket3/
@@ -63,7 +63,7 @@ def parse(conn): # Обработка соединения в отдельно
6363
sock.bind(("", PORT))
6464
sock.listen()
6565

66-
print(f'HTTP server running on http://127.0.0.1:{PORT}/time.html')
66+
print(f"HTTP server running on http://127.0.0.1:{PORT}/time.html")
6767

6868
try:
6969
# Работаем постоянно

socket__tcp__examples/http_server__threading.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
# SOURCE: http://andreymal.org/socket3/
88

9-
import time
9+
1010
import socket
11+
import time
12+
1113
from threading import Thread
1214

1315

@@ -66,19 +68,19 @@ def parse(conn): # Обработка соединения в отдельно
6668
conn.close()
6769

6870

69-
HOST = 'localhost'
71+
HOST = "localhost"
7072
PORT = 9090
7173

7274

73-
if __name__ == '__main__':
75+
if __name__ == "__main__":
7476
sock = socket.socket()
75-
print('Socket created')
77+
print("Socket created")
7678

7779
sock.bind((HOST, PORT))
78-
print('Socket bind complete')
80+
print("Socket bind complete")
7981

8082
sock.listen()
81-
print('Socket now listening: http://{}:{}'.format(*sock.getsockname()))
83+
print("Socket now listening: http://{}:{}".format(*sock.getsockname()))
8284
print()
8385

8486
try:

socket__tcp__examples/https__get__with_urlsplit.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,33 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

7-
from urllib.parse import urlsplit
87
import socket
98
import ssl
109

10+
from urllib.parse import urlsplit
11+
1112

1213
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
13-
url = 'https://www.coursera.org/robots.txt'
14+
url = "https://www.coursera.org/robots.txt"
1415

1516
result = urlsplit(url)
1617

1718
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
1819
s_sock = context.wrap_socket(socket, server_hostname=result.netloc)
1920
s_sock.connect((result.netloc, 443))
2021

21-
cmd = f'GET {result.path} HTTP/1.1\r\nHost: {result.netloc}\r\n\r\n'.encode()
22+
cmd = f"GET {result.path} HTTP/1.1\r\nHost: {result.netloc}\r\n\r\n".encode()
2223
s_sock.send(cmd)
2324

2425
while True:
2526
data = s_sock.recv(512)
2627
if not data:
2728
break
2829

29-
print(data.decode(), end='')
30+
print(data.decode(), end="")
3031

3132
s_sock.close()
3233

0 commit comments

Comments
 (0)