Created
September 23, 2024 08:26
-
-
Save tepel-chen/230fdc4349f1244b303049446290c494 to your computer and use it in GitHub Desktop.
raw_request.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import socket | |
| import requests | |
| from urllib.parse import urlparse | |
| from collections.abc import Iterable | |
| def raw_request(url: str=None, host: str=None, port: int=None, strs: Iterable[str] | str=None): | |
| if isinstance(url, str): | |
| url = urlparse(url) | |
| host = url.hostname | |
| port = url.port | |
| sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| sock.connect((host, port)) | |
| if isinstance(strs, Iterable) and not isinstance(strs, str): | |
| strs = "\r\n".join(strs) | |
| while strs[-4:] != "\r\n\r\n": | |
| strs += "\r\n" | |
| sock.send(strs.encode()) | |
| response_data = b"" | |
| buffer_size = 4096 | |
| while True: | |
| part = sock.recv(buffer_size) | |
| response_data += part | |
| if len(part) < buffer_size: | |
| break | |
| response = requests.Response() | |
| response.raw = response_data | |
| header_data, body = response_data.split(b"\r\n\r\n", 1) | |
| header_lines = header_data.split(b"\r\n") | |
| status_line = header_lines[0] | |
| _, status_code, _ = status_line.split(b" ", 2) | |
| response.status_code = int(status_code) | |
| headers = {} | |
| for header_line in header_lines[1:]: | |
| key, value = header_line.split(b": ", 1) | |
| headers[key] = value | |
| response.headers = headers | |
| response._content = body | |
| response.encoding = 'utf-8' | |
| response.url = f"http://{sock.getpeername()[0]}" | |
| return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment